diff --git "a/sft_data.jsonl" "b/sft_data.jsonl" --- "a/sft_data.jsonl" +++ "b/sft_data.jsonl" @@ -2248,3 +2248,253 @@ {"prompt": [{"role": "user", "content": "Write a function `calculate_net_pay(gross_pay, federal_rate, state_rate, pretax_deductions)` that computes an employee's net pay for one pay period. First, subtract `pretax_deductions` (e.g., health insurance premiums) from `gross_pay` to get taxable wages. Then compute federal withholding as `taxable_wages * federal_rate` and state withholding as `taxable_wages * state_rate`. All money values must be handled with `Decimal`, and each result must be rounded to exactly 2 decimal places using ROUND_HALF_UP. Return a dict with keys 'taxable_wages', 'federal_withholding', 'state_withholding', 'net_pay', where net_pay = taxable_wages - federal_withholding - state_withholding. For example, with gross_pay='3200.00', federal_rate='0.15', state_rate='0.04', pretax_deductions='250.00', the result is {'taxable_wages': '2950.00', 'federal_withholding': '442.50', 'state_withholding': '118.00', 'net_pay': '2389.50'}. Inputs may be given as strings or numbers; convert them to Decimal. Raise ValueError if gross_pay or pretax_deductions is negative, or if either tax rate is not between 0 and 1 inclusive."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef calculate_net_pay(gross_pay, federal_rate, state_rate, pretax_deductions):\n gross = Decimal(str(gross_pay))\n fed_rate = Decimal(str(federal_rate))\n st_rate = Decimal(str(state_rate))\n pretax = Decimal(str(pretax_deductions))\n\n if gross < 0 or pretax < 0:\n raise ValueError('Gross pay and pre-tax deductions must be non-negative')\n if not (Decimal(0) <= fed_rate <= Decimal(1)) or not (Decimal(0) <= st_rate <= Decimal(1)):\n raise ValueError('Tax rates must be between 0 and 1 inclusive')\n\n taxable = gross - pretax\n if taxable < 0:\n taxable = Decimal('0.00')\n\n federal = (taxable * fed_rate).quantize(TWO, rounding=ROUND_HALF_UP)\n state = (taxable * st_rate).quantize(TWO, rounding=ROUND_HALF_UP)\n taxable_q = taxable.quantize(TWO, rounding=ROUND_HALF_UP)\n net = (taxable_q - federal - state).quantize(TWO, rounding=ROUND_HALF_UP)\n\n return {\n 'taxable_wages': str(taxable_q),\n 'federal_withholding': str(federal),\n 'state_withholding': str(state),\n 'net_pay': str(net),\n }\n\nif __name__ == '__main__':\n result = calculate_net_pay('3200.00', '0.15', '0.04', '250.00')\n print(result)\n assert result == {'taxable_wages': '2950.00', 'federal_withholding': '442.50', 'state_withholding': '118.00', 'net_pay': '2389.50'}"}], "meta": {"idx": 2249, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "novita", "in_tokens": 200, "out_tokens": 743, "latency_s": 7.8}} {"prompt": [{"role": "user", "content": "Implement a simple ledger with precise money handling and write unit tests for it. Create a class `Ledger` with methods `add_entry(description, amount)` (where `amount` is a `Decimal` or string), `balance()` returning the net balance as a `Decimal` rounded to 2 decimal places with ROUND_HALF_UP, and `total_debits()` / `total_credits()` returning the sum of positive amounts (debits) and the absolute sum of negative amounts (credits) respectively, each rounded to 2 decimal places. Reject amounts with more than 2 decimal places by raising `ValueError`. Example: adding entries '10.005' must raise ValueError, while entries '12.345' minus... more precisely: adding '10.00', '-3.50', and '5.25' gives balance() == Decimal('11.75'), total_debits() == Decimal('15.25'), and total_credits() == Decimal('3.50'). Write unit tests using the standard library `unittest` module covering: normal additions, the rounding of balance to 2 places, the ValueError for too many decimal places, an empty ledger returning 0.00, and the worked example above."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom decimal import Decimal, ROUND_HALF_UP, InvalidOperation\n\n\nclass Ledger:\n def __init__(self):\n self._entries = []\n\n def add_entry(self, description, amount):\n if not isinstance(amount, Decimal):\n try:\n amount = Decimal(str(amount))\n except InvalidOperation:\n raise ValueError(f\"Invalid monetary amount: {amount!r}\")\n if not amount.is_finite():\n raise ValueError(f\"Invalid monetary amount: {amount!r}\")\n if -amount.as_tuple().exponent < -2 and amount != amount.quantize(Decimal('0.01')):\n raise ValueError(f\"Amount {amount} has more than 2 decimal places\")\n self._entries.append((description, amount))\n\n @staticmethod\n def _round(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n def balance(self):\n return self._round(sum((e[1] for e in self._entries), Decimal('0')))\n\n def total_debits(self):\n return self._round(sum((e[1] for e in self._entries if e[1] > 0), Decimal('0')))\n\n def total_credits(self):\n return self._round(sum((-e[1] for e in self._entries if e[1] < 0), Decimal('0')))\n\n\nclass TestLedger(unittest.TestCase):\n def test_empty_ledger(self):\n ledger = Ledger()\n self.assertEqual(ledger.balance(), Decimal('0.00'))\n self.assertEqual(ledger.total_debits(), Decimal('0.00'))\n self.assertEqual(ledger.total_credits(), Decimal('0.00'))\n\n def test_normal_additions(self):\n ledger = Ledger()\n ledger.add_entry('sale', '100.10')\n ledger.add_entry('refund', '-40.05')\n self.assertEqual(ledger.balance(), Decimal('60.05'))\n self.assertEqual(ledger.total_debits(), Decimal('100.10'))\n self.assertEqual(ledger.total_credits(), Decimal('40.05'))\n\n def test_worked_example(self):\n ledger = Ledger()\n ledger.add_entry('a', '10.00')\n ledger.add_entry('b', '-3.50')\n ledger.add_entry('c', '5.25')\n self.assertEqual(ledger.balance(), Decimal('11.75'))\n self.assertEqual(ledger.total_debits(), Decimal('15.25'))\n self.assertEqual(ledger.total_credits(), Decimal('3.50'))\n\n def test_balance_rounding(self):\n ledger = Ledger()\n ledger.add_entry('x', '0.005')\n self.assertEqual(ledger.balance(), Decimal('0.01'))\n ledger2 = Ledger()\n ledger2.add_entry('y', '0.004')\n self.assertEqual(ledger2.balance(), Decimal('0.00'))\n\n def test_too_many_decimals_raises(self):\n ledger = Ledger()\n with self.assertRaises(ValueError):\n ledger.add_entry('bad', '10.005')\n with self.assertRaises(ValueError):\n ledger.add_entry('bad', '1.234')\n\n\nif __name__ == '__main__':\n unittest.main()"}], "meta": {"idx": 2244, "topic": "unit tests for accounting functions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 984, "latency_s": 32.5}} {"prompt": [{"role": "user", "content": "Write a function `find_duplicate_debits(entries)` that scans a bookkeeper's debit ledger for duplicate or anomalous debit entries. Each entry is a tuple `(date, description, amount)` where `date` is a string 'YYYY-MM-DD', `description` is a string, and `amount` is a string representing a monetary value (use Decimal to parse it, quantized to 2 places with ROUND_HALF_UP). An entry is flagged as a duplicate if another entry in the list has the same date, the same description, and an equal quantized amount. Additionally, flag any entry whose amount is negative as anomalous. The function should return a list of the 0-based indices of all flagged entries, in ascending order, with no index repeated. Example: entries = [('2024-01-05', 'Office supplies', '12.50'), ('2024-01-05', 'Office supplies', '12.505'), ('2024-01-05', 'Office supplies', '12.51'), ('2024-01-06', 'Rent', '-500.00')] returns [0, 1, 3] because entries 0 and 1 both quantize to 12.50 on the same date/description (duplicates), while entry 2 differs (12.51) and entry 3 is flagged for being negative."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\n\ndef find_duplicate_debits(entries):\n TWO = Decimal('0.01')\n\n def quantize(amount_str):\n return Decimal(amount_str).quantize(TWO, rounding=ROUND_HALF_UP)\n\n groups = defaultdict(list)\n for idx, (date, desc, amount_str) in enumerate(entries):\n key = (date, desc, quantize(amount_str))\n groups[key].append(idx)\n\n flagged = set()\n for key, indices in groups.items():\n if len(indices) > 1:\n flagged.update(indices)\n\n for idx, (date, desc, amount_str) in enumerate(entries):\n if quantize(amount_str) < 0:\n flagged.add(idx)\n\n return sorted(flagged)\n\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-05', 'Office supplies', '12.50'),\n ('2024-01-05', 'Office supplies', '12.505'),\n ('2024-01-05', 'Office supplies', '12.51'),\n ('2024-01-06', 'Rent', '-500.00'),\n ]\n print(find_duplicate_debits(entries)) # [0, 1, 3]"}], "meta": {"idx": 2253, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 537, "latency_s": 5.9}} +{"prompt": [{"role": "user", "content": "Write a command-line bookkeeping tool that processes a ledger of transactions and produces a per-account balance report. Input consists of lines in the format `DATE|ACCOUNT|AMOUNT`, where DATE is `YYYY-MM-DD`, ACCOUNT is a name like `cash` or `expenses:rent`, and AMOUNT is a decimal number that may be negative (debits decrease, credits increase the account balance). All amounts must be handled with the `decimal.Decimal` type, and the final balances must be rounded to exactly 2 decimal places using `ROUND_HALF_UP`. Accounts should appear in the report sorted alphabetically, formatted as `ACCOUNT: BALANCE` with the balance always shown with two decimals (e.g., `-12.50`). Skip blank lines and lines that are malformed (wrong number of fields or an invalid amount or date), and skip them silently. For example, the input `2024-01-05|cash|100.00` followed by `2024-01-10|expenses:rent|-80.005` and a blank line must produce the report `cash: 100.00` and `expenses:rent: -80.01` (since -80.005 rounds half-up away from zero). Read input lines from stdin and print the report to stdout."}], "completion": [{"role": "assistant", "content": "import sys\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom datetime import datetime\n\n\ndef is_valid_date(s):\n try:\n datetime.strptime(s, \"%Y-%m-%d\")\n return True\n except ValueError:\n return False\n\n\ndef is_valid_amount(s):\n try:\n Decimal(s)\n return True\n except Exception:\n return False\n\n\ndef main():\n balances = {}\n for raw in sys.stdin:\n line = raw.strip()\n if not line:\n continue\n parts = line.split(\"|\")\n if len(parts) != 3:\n continue\n date, account, amount = (p.strip() for p in parts)\n if not is_valid_date(date) or not is_valid_amount(amount):\n continue\n if not account:\n continue\n balances[account] = balances.get(account, Decimal(\"0\")) + Decimal(amount)\n for account in sorted(balances):\n rounded = balances[account].quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP)\n print(f\"{account}: {rounded:.2f}\")\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2254, "topic": "small bookkeeping command-line tool logic", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 550, "latency_s": 5.6}} +{"prompt": [{"role": "user", "content": "You are auditing a general ledger given as a list of journal entries, where each entry is a dict with keys id, date (ISO 'YYYY-MM-DD'), memo, and lines; each line has account, debit, and credit given as decimal digit strings. Using Decimal with ROUND_HALF_UP quantization to cents, produce an audit report (a dict returned by a function audit(entries)) with five findings: (1) 'exact_duplicates' \u2014 ids of entries whose (date, memo, sorted list of quantized (account, debit, credit) lines) signature matches an earlier entry; (2) 'near_duplicates' \u2014 pairs [earlier_id, later_id] of entries not already flagged as exact duplicates that share the same memo and the same quantized debit total, with dates no more than 3 calendar days apart; (3) 'unbalanced' \u2014 ids whose quantized debit total differs from its quantized credit total; (4) 'subcent' \u2014 ids containing any line amount with more than two decimal places; (5) 'benford_flags' \u2014 accounts having at least 30 nonzero quantized amounts whose first-significant-digit counts deviate from Benford's law with a chi-square statistic exceeding 15.507. Worked example: E1 and E2 both dated 2024-03-01 with memo 'March rent' and lines (Rent Expense debit 1500.00, Cash credit 1500.00); E3 dated 2024-03-02 with memo 'March rent' and lines (Rent Expense debit 1500.00, Accounts Payable credit 1500.00); E4 dated 2024-03-05 with memo 'Client payment' and lines (Cash debit 2750.55, Revenue credit 2750.55, Bank Fee debit 12.50); E5 dated 2024-03-10 with memo 'Consulting fee' and lines (Consulting Expense debit 1000.001, Cash credit 1000.00). The expected report is {'exact_duplicates': ['E2'], 'near_duplicates': [['E1', 'E3']], 'unbalanced': ['E4'], 'subcent': ['E5'], 'benford_flags': []}. Every list in the report must be deterministically sorted, and the solution must use only the standard library."}], "completion": [{"role": "assistant", "content": "import json\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom math import log10\n\nCENT = Decimal(\"0.01\")\nBENFORD_THRESHOLD = Decimal(\"15.507\")\nMIN_BENFORD_COUNT = 30\nNEAR_DUP_DAYS = 3\n\n\ndef _q(x):\n \"\"\"Quantize a Decimal to cents using banker-safe half-up rounding.\"\"\"\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _parse_date(s):\n y, m, d = s.split(\"-\")\n return date(int(y), int(m), int(d))\n\n\ndef _first_digit(x):\n digits = format(abs(x), \"f\").replace(\".\", \"\").lstrip(\"0\")\n return int(digits[0]) if digits else None\n\n\ndef _signature(entry):\n lines = tuple(sorted(\n (ln[\"account\"], str(_q(Decimal(ln[\"debit\"]))), str(_q(Decimal(ln[\"credit\"]))))\n for ln in entry[\"lines\"]\n ))\n return (entry[\"date\"], entry[\"memo\"], lines)\n\n\ndef audit(entries):\n # 1) Exact duplicates: identical signature to an earlier entry.\n exact = []\n seen = {}\n for e in entries:\n sig = _signature(e)\n if sig in seen:\n exact.append(e[\"id\"])\n else:\n seen[sig] = e[\"id\"]\n exact_set = set(exact)\n\n # 2) Near duplicates: same memo and debit total, dates within 3 days,\n # excluding entries already flagged as exact duplicates.\n near = []\n active = [e for e in entries if e[\"id\"] not in exact_set]\n totals = {\n e[\"id\"]: sum((_q(Decimal(ln[\"debit\"])) for ln in e[\"lines\"]), Decimal(\"0\"))\n for e in active\n }\n for i in range(len(active)):\n for j in range(i + 1, len(active)):\n a, b = active[i], active[j]\n if a[\"memo\"] != b[\"memo\"]:\n continue\n if totals[a[\"id\"]] != totals[b[\"id\"]]:\n continue\n delta = abs((_parse_date(a[\"date\"]) - _parse_date(b[\"date\"])).days)\n if delta <= NEAR_DUP_DAYS:\n near.append([a[\"id\"], b[\"id\"]])\n\n # 3) Unbalanced entries and 4) sub-cent precision anomalies.\n unbalanced = []\n subcent = []\n for e in entries:\n debit_total = Decimal(\"0\")\n credit_total = Decimal(\"0\")\n has_subcent = False\n for ln in e[\"lines\"]:\n d = Decimal(ln[\"debit\"])\n c = Decimal(ln[\"credit\"])\n debit_total += _q(d)\n credit_total += _q(c)\n if d != _q(d) or c != _q(c):\n has_subcent = True\n if debit_total != credit_total:\n unbalanced.append(e[\"id\"])\n if has_subcent:\n subcent.append(e[\"id\"])\n\n # 5) Benford's-law screening per account.\n account_amounts = {}\n for e in entries:\n for ln in e[\"lines\"]:\n for raw in (Decimal(ln[\"debit\"]), Decimal(ln[\"credit\"])):\n v = _q(raw)\n if v != 0:\n account_amounts.setdefault(ln[\"account\"], []).append(v)\n benford = []\n for acct in sorted(account_amounts):\n vals = account_amounts[acct]\n n = len(vals)\n if n < MIN_BENFORD_COUNT:\n continue\n counts = [0] * 10\n for v in vals:\n fd = _first_digit(v)\n if fd is not None:\n counts[fd] += 1\n chi = Decimal(\"0\")\n for d in range(1, 10):\n expected = Decimal(str(log10(1 + 1 / d))) * n\n observed = Decimal(counts[d])\n chi += (observed - expected) ** 2 / expected\n if chi > BENFORD_THRESHOLD:\n benford.append(acct)\n\n return {\n \"exact_duplicates\": sorted(exact),\n \"near_duplicates\": sorted(near),\n \"unbalanced\": sorted(unbalanced),\n \"subcent\": sorted(subcent),\n \"benford_flags\": benford,\n }\n\n\nif __name__ == \"__main__\":\n ledger = [\n {\n \"id\": \"E1\", \"date\": \"2024-03-01\", \"memo\": \"March rent\",\n \"lines\": [\n {\"account\": \"Rent Expense\", \"debit\": \"1500.00\", \"credit\": \"0.00\"},\n {\"account\": \"Cash\", \"debit\": \"0.00\", \"credit\": \"1500.00\"},\n ],\n },\n {\n \"id\": \"E2\", \"date\": \"2024-03-01\", \"memo\": \"March rent\",\n \"lines\": [\n {\"account\": \"Rent Expense\", \"debit\": \"1500.00\", \"credit\": \"0.00\"},\n {\"account\": \"Cash\", \"debit\": \"0.00\", \"credit\": \"1500.00\"},\n ],\n },\n {\n \"id\": \"E3\", \"date\": \"2024-03-02\", \"memo\": \"March rent\",\n \"lines\": [\n {\"account\": \"Rent Expense\", \"debit\": \"1500.00\", \"credit\": \"0.00\"},\n {\"account\": \"Accounts Payable\", \"debit\": \"0.00\", \"credit\": \"1500.00\"},\n ],\n },\n {\n \"id\": \"E4\", \"date\": \"2024-03-05\", \"memo\": \"Client payment\",\n \"lines\": [\n {\"account\": \"Cash\", \"debit\": \"2750.55\", \"credit\": \"0.00\"},\n {\"account\": \"Revenue\", \"debit\": \"0.00\", \"credit\": \"2750.55\"},\n {\"account\": \"Bank Fee\", \"debit\": \"12.50\", \"credit\": \"0.00\"},\n ],\n },\n {\n \"id\": \"E5\", \"date\": \"2024-03-10\", \"memo\": \"Consulting fee\",\n \"lines\": [\n {\"account\": \"Consulting Expense\", \"debit\": \"1000.001\", \"credit\": \"0.00\"},\n {\"account\": \"Cash\", \"debit\": \"0.00\", \"credit\": \"1000.00\"},\n ],\n },\n ]\n print(json.dumps(audit(ledger), indent=2))"}], "meta": {"idx": 2236, "topic": "detecting duplicate or anomalous transactions", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1897, "latency_s": 43.0}} +{"prompt": [{"role": "user", "content": "A company keeps a petty cash log. The fund starts with a fixed opening balance, and each entry is either a disbursement (money paid out, recorded as a positive amount) or a cash addition (money put in, recorded as a negative amount). Write a function `replenish_needed(opening_balance, entries)` that takes the opening balance as a string and a list of (label, amount_string) tuples, and returns a dict with three keys: 'current_balance', 'total_disbursed', and 'replenish_amount'. Use Decimal arithmetic with two-decimal quantization (ROUND_HALF_UP) for all money values. The current balance equals opening_balance minus total disbursements plus total additions; replenish_amount is the amount needed to restore the fund to the opening balance (0 if the balance already equals or exceeds it). For example, with opening_balance '100.00' and entries [('taxi','25.50'), ('postage','10.25'), ('cash-in','-5.00')], the result is {'current_balance': '69.25', 'total_disbursed': '35.75', 'replenish_amount': '30.75'}. All returned amounts must be strings with exactly two decimal places."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef q(d):\n return d.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef replenish_needed(opening_balance, entries):\n opening = q(Decimal(opening_balance))\n disbursed = Decimal('0')\n additions = Decimal('0')\n for _label, amt in entries:\n a = Decimal(amt)\n if a > 0:\n disbursed += a\n else:\n additions += -a\n disbursed = q(disbursed)\n additions = q(additions)\n balance = q(opening - disbursed + additions)\n replenish = q(opening - balance)\n if replenish < 0:\n replenish = Decimal('0.00')\n return {\n 'current_balance': str(balance),\n 'total_disbursed': str(disbursed),\n 'replenish_amount': str(replenish),\n }\n\nif __name__ == '__main__':\n result = replenish_needed('100.00', [('taxi', '25.50'), ('postage', '10.25'), ('cash-in', '-5.00')])\n print(result)\n assert result == {'current_balance': '69.25', 'total_disbursed': '35.75', 'replenish_amount': '30.75'}"}], "meta": {"idx": 2255, "topic": "petty cash logs and replenishment", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 544, "latency_s": 6.2}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, life, rate=None)` that produces a depreciation schedule for an asset. If `rate` is None, use straight-line depreciation: each year's depreciation is (cost - salvage) / life, applied for exactly `life` years, leaving the book value at salvage. If `rate` is given (e.g. 0.4 for double-declining balance), use the declining-balance method: each year depreciate `rate * current_book_value`, but never depreciate below the salvage value (the final year's depreciation is capped so book value ends exactly at salvage). All monetary values must be handled with `Decimal` and rounded to 2 decimal places at each yearly entry. Return a list of tuples `(year, depreciation, book_value)` where year starts at 1. Example: cost=Decimal('1000.00'), salvage=Decimal('100.00'), life=3, rate=Decimal('0.5') gives [(1, Decimal('500.00'), Decimal('500.00')), (2, Decimal('250.00'), Decimal('250.00')), (3, Decimal('150.00'), Decimal('100.00'))]. For straight-line with the same cost/salvage/life and rate=None, the schedule is [(1, Decimal('300.00'), Decimal('700.00')), (2, Decimal('300.00'), Decimal('400.00')), (3, Decimal('300.00'), Decimal('100.00'))]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef depreciation_schedule(cost, salvage, life, rate=None):\n cost = Decimal(cost)\n salvage = Decimal(salvage)\n schedule = []\n\n if rate is None:\n yearly = _round2((cost - salvage) / Decimal(life))\n book = cost\n for year in range(1, int(life) + 1):\n if year == int(life):\n dep = _round2(book - salvage)\n else:\n dep = yearly\n book = _round2(book - dep)\n schedule.append((year, dep, book))\n return schedule\n\n rate = Decimal(rate)\n book = cost\n for year in range(1, int(life) + 1):\n dep = _round2(rate * book)\n if book - dep < salvage:\n dep = _round2(book - salvage)\n book = _round2(book - dep)\n schedule.append((year, dep, book))\n return schedule\n\n\nif __name__ == '__main__':\n print(depreciation_schedule('1000.00', '100.00', 3, rate='0.5'))\n print(depreciation_schedule('1000.00', '100.00', 3))"}], "meta": {"idx": 2256, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 591, "latency_s": 5.1}} +{"prompt": [{"role": "user", "content": "Write a function `amortization_schedule(principal, annual_rate, months)` that builds a loan amortization ledger using the `decimal.Decimal` type with two-decimal rounding (ROUND_HALF_UP). The loan has a fixed monthly payment made at the end of each month, computed as `principal * i / (1 - (1+i)**-months)` where `i` is the monthly interest rate (annual rate divided by 12); the final payment must be adjusted so the ending balance is exactly zero. Each month, interest is `balance * i` rounded to cents, the payment is applied to interest first then principal, and every entry must be recorded to the cent. Return a list of dictionaries, one per month, with keys 'month', 'payment', 'interest', 'principal', 'balance' (balance is the remaining debt after that month's payment). For example, for principal=Decimal('1000.00'), annual_rate=Decimal('0.12'), months=3: the monthly payment computes to Decimal('340.03'), and the schedule is month 1: interest 10.00, principal 330.03, balance 669.97; month 2: interest 6.70, principal 333.33, balance 336.64; month 3: payment 340.02, interest 3.37, principal 336.64, balance 0.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\nONE = Decimal('1')\nTWELVE = Decimal('12')\n\n\ndef _round(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef amortization_schedule(principal, annual_rate, months):\n principal = Decimal(str(principal))\n i = Decimal(str(annual_rate)) / TWELVE\n months = int(months)\n\n if i == 0:\n base_payment = _round(principal / Decimal(months))\n else:\n factor = (ONE + i) ** Decimal(-months)\n base_payment = _round(principal * i / (ONE - factor))\n\n schedule = []\n balance = _round(principal)\n for month in range(1, months + 1):\n interest = _round(balance * i)\n if month == months:\n payment = _round(balance + interest)\n else:\n payment = base_payment\n principal_part = payment - interest\n if principal_part > balance:\n principal_part = balance\n payment = _round(balance + interest)\n balance = _round(balance - principal_part)\n schedule.append({\n 'month': month,\n 'payment': _round(payment),\n 'interest': interest,\n 'principal': _round(principal_part),\n 'balance': balance,\n })\n return schedule\n\n\nif __name__ == '__main__':\n for row in amortization_schedule(Decimal('1000.00'), Decimal('0.12'), 3):\n print(row)\n # Expected:\n # {'month': 1, 'payment': Decimal('340.03'), 'interest': Decimal('10.00'), 'principal': Decimal('330.03'), 'balance': Decimal('669.97')}\n # {'month': 2, 'payment': Decimal('340.03'), 'interest': Decimal('6.70'), 'principal': Decimal('333.33'), 'balance': Decimal('336.64')}\n # {'month': 3, 'payment': Decimal('340.02'), 'interest': Decimal('3.37'), 'principal': Decimal('336.64'), 'balance': Decimal('0.00')}"}], "meta": {"idx": 2250, "topic": "loan and mortgage amortization schedules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 758, "latency_s": 18.7}} +{"prompt": [{"role": "user", "content": "You are building a small chart of accounts for a bookkeeping app. Write a function `categorize_expenses(entries)` that takes a list of tuples `(account_name, amount_str)`, where `account_name` is a string like 'Office Supplies' and `amount_str` is a string like '45.67'. Group all amounts by account name using `Decimal` for exact arithmetic, and return a dict mapping each account name to its total, rounded to 2 decimal places with ROUND_HALF_UP. If a list is empty, return an empty dict. For example, given [('Office Supplies', '45.67'), ('Rent', '1200.00'), ('Office Supplies', '12.33')], the result is {'Office Supplies': Decimal('58.00'), 'Rent': Decimal('1200.00')}. Invalid amounts (e.g. 'abc') should raise a `ValueError`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\n\ndef categorize_expenses(entries):\n \"\"\"Group expense amounts by account name.\n\n Args:\n entries: list of (account_name, amount_str) tuples.\n\n Returns:\n dict mapping account name to Decimal total rounded to 2 places\n (ROUND_HALF_UP). Raises ValueError for invalid amounts.\n \"\"\"\n totals = defaultdict(Decimal)\n for account_name, amount_str in entries:\n try:\n amount = Decimal(amount_str)\n except Exception:\n raise ValueError(f\"Invalid amount for account {account_name!r}: {amount_str!r}\")\n totals[account_name] += amount\n return {\n name: total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n for name, total in totals.items()\n }\n\n\nif __name__ == '__main__':\n entries = [('Office Supplies', '45.67'), ('Rent', '1200.00'), ('Office Supplies', '12.33')]\n print(categorize_expenses(entries))\n # {'Office Supplies': Decimal('58.00'), 'Rent': Decimal('1200.00')}\n print(categorize_expenses([]))\n # {}"}], "meta": {"idx": 2262, "topic": "chart of accounts and expense categorization", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 474, "latency_s": 7.1}} +{"prompt": [{"role": "user", "content": "Implement a general ledger with T-account support using Decimal arithmetic. Each account has a normal balance side ('debit' or 'credit'). Post journal entries (each entry is a list of (account_name, 'debit'|'credit', amount) lines) to the ledger, rejecting any entry whose debits do not equal its credits. After posting, compute each account's balance as a signed amount: positive if it agrees with the account's normal balance side, negative otherwise. Then produce a trial balance report: two columns of totals, debits and credits, showing each account's balance on the side it lands on (a positive balance on a debit-normal account appears in the debit column; a negative balance on a debit-normal account appears in the credit column), and verify the two column totals are equal. Round all amounts to 2 decimal places using ROUND_HALF_UP. Example: accounts 'Cash' (debit-normal) and 'Revenue' (credit-normal); entry [('Cash','debit','100.00'), ('Revenue','credit','100.00')]; Cash balance is Decimal('100.00') shown in the debit column, Revenue balance is Decimal('100.00') shown in the credit column; both trial balance totals equal Decimal('100.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef q(amount):\n return Decimal(amount).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\nclass Ledger:\n def __init__(self):\n self.accounts = {} # name -> {'normal': 'debit'|'credit', 'debit': D, 'credit': D}\n\n def add_account(self, name, normal_side):\n if normal_side not in ('debit', 'credit'):\n raise ValueError(\"normal_side must be 'debit' or 'credit'\")\n if name in self.accounts:\n raise ValueError('account already exists: %s' % name)\n self.accounts[name] = {'normal': normal_side,\n 'debit': Decimal('0.00'),\n 'credit': Decimal('0.00')}\n\n def post_entry(self, lines):\n debits = Decimal('0.00')\n credits = Decimal('0.00')\n checked = []\n for name, side, amount in lines:\n if name not in self.accounts:\n raise ValueError('unknown account: %s' % name)\n if side not in ('debit', 'credit'):\n raise ValueError(\"side must be 'debit' or 'credit'\")\n amt = q(amount)\n if amt <= 0:\n raise ValueError('amount must be positive')\n checked.append((name, side, amt))\n if side == 'debit':\n debits += amt\n else:\n credits += amt\n if debits != credits:\n raise ValueError('unbalanced entry: debits %s != credits %s' % (debits, credits))\n for name, side, amt in checked:\n self.accounts[name][side] += amt\n\n def balance(self, name):\n acct = self.accounts[name]\n d, c = acct['debit'], acct['credit']\n if acct['normal'] == 'debit':\n return q(d - c)\n return q(c - d)\n\n def trial_balance(self):\n debit_col = {}\n credit_col = {}\n for name in sorted(self.accounts):\n bal = self.balance(name)\n normal = self.accounts[name]['normal']\n if bal >= 0:\n (debit_col if normal == 'debit' else credit_col)[name] = bal\n else:\n (credit_col if normal == 'debit' else debit_col)[name] = -bal\n total_d = q(sum(debit_col.values(), Decimal('0.00')))\n total_c = q(sum(credit_col.values(), Decimal('0.00')))\n return {'debit_column': debit_col, 'credit_column': credit_col,\n 'total_debits': total_d, 'total_credits': total_c,\n 'balanced': total_d == total_c}\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add_account('Cash', 'debit')\n ledger.add_account('Revenue', 'credit')\n ledger.post_entry([('Cash', 'debit', '100.00'), ('Revenue', 'credit', '100.00')])\n tb = ledger.trial_balance()\n assert ledger.balance('Cash') == Decimal('100.00')\n assert ledger.balance('Revenue') == Decimal('100.00')\n assert tb['total_debits'] == Decimal('100.00')\n assert tb['total_credits'] == Decimal('100.00')\n assert tb['balanced']\n print(tb)"}], "meta": {"idx": 2260, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1073, "latency_s": 10.3}} +{"prompt": [{"role": "user", "content": "Write a function `compute_net_pay(gross, federal_rate, state_rate, pre_tax_deductions, post_tax_deductions)` that computes an employee's net pay from a paycheck. The gross pay is first reduced by pre-tax deductions (e.g., 401k, health premiums); federal and state withholding taxes are then computed as percentages (given as Decimal-friendly strings or numbers) of that reduced taxable amount, rounded to the nearest cent with ROUND_HALF_UP. Post-tax deductions (e.g., garnishments, union dues) are subtracted after taxes. All arithmetic must use `decimal.Decimal` to avoid floating-point errors, and every output amount must be rounded to 2 decimal places with ROUND_HALF_UP. The function returns a dict with keys 'taxable_gross', 'federal_tax', 'state_tax', 'total_deductions', and 'net_pay'. Example: gross=2500.00, federal_rate='22%', state_rate='5%', pre_tax_deductions=300.00, post_tax_deductions=50.00 gives taxable_gross=2200.00, federal_tax=484.00, state_tax=110.00, total_deductions=944.00, net_pay=1556.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _to_decimal(value):\n \"\"\"Convert a string, int, float, or Decimal to Decimal safely.\"\"\"\n if isinstance(value, Decimal):\n return value\n if isinstance(value, float):\n return Decimal(str(value))\n return Decimal(str(value))\n\n\ndef _round_cent(value):\n \"\"\"Round a Decimal to 2 decimal places using ROUND_HALF_UP.\"\"\"\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef _to_rate(value):\n \"\"\"Convert a rate like '22%', 22 (percent), 0.22, or '0.22' to a Decimal fraction.\"\"\"\n d = _to_decimal(value)\n s = str(value).strip()\n if s.endswith('%'):\n return _to_decimal(s[:-1].strip()) / Decimal('100')\n # If given as a plain number, treat it as a percentage (22 means 22%).\n return d / Decimal('100')\n\n\ndef compute_net_pay(gross, federal_rate, state_rate, pre_tax_deductions, post_tax_deductions):\n gross_d = _to_decimal(gross)\n pre_tax_d = _to_decimal(pre_tax_deductions)\n post_tax_d = _to_decimal(post_tax_deductions)\n\n federal_frac = _to_rate(federal_rate)\n state_frac = _to_rate(state_rate)\n\n # Taxable gross: gross minus pre-tax deductions (not below zero).\n taxable_gross = _round_cent(max(gross_d - pre_tax_d, Decimal('0.00')))\n\n # Withholdings computed on the taxable gross, each rounded to the cent.\n federal_tax = _round_cent(taxable_gross * federal_frac)\n state_tax = _round_cent(taxable_gross * state_frac)\n\n # Total deductions: pre-tax + taxes + post-tax.\n total_deductions = _round_cent(\n pre_tax_d + federal_tax + state_tax + post_tax_d\n )\n\n # Net pay: gross minus all deductions.\n net_pay = _round_cent(gross_d - total_deductions)\n\n return {\n 'taxable_gross': taxable_gross,\n 'federal_tax': federal_tax,\n 'state_tax': state_tax,\n 'total_deductions': total_deductions,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = compute_net_pay(\n gross='2500.00',\n federal_rate='22%',\n state_rate='5%',\n pre_tax_deductions='300.00',\n post_tax_deductions='50.00',\n )\n for key, value in result.items():\n print(f'{key}: {value}')\n # Expected: taxable_gross=2200.00, federal_tax=484.00, state_tax=110.00,\n # total_deductions=944.00, net_pay=1556.00\n assert result['taxable_gross'] == Decimal('2200.00')\n assert result['federal_tax'] == Decimal('484.00')\n assert result['state_tax'] == Decimal('110.00')\n assert result['total_deductions'] == Decimal('944.00')\n assert result['net_pay'] == Decimal('1556.00')\n print('All checks passed.')"}], "meta": {"idx": 2261, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 944, "latency_s": 11.8}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts as a list of tuples (account_code, account_name, normal_balance) where normal_balance is 'debit' or 'credit', and a list of transactions, each a tuple (account_code, description, amount_string). Amounts may be negative, meaning the opposite side of the account's normal balance (e.g., a negative amount on a debit-normal expense account is a credit). Write a function `trial_balance(accounts, transactions)` that: (1) raises ValueError if a transaction references an unknown account code; (2) computes each account's balance in cents using Decimal with ROUND_HALF_UP rounding to 2 decimal places after each transaction is applied; (3) returns a dict mapping account_code to a Decimal balance expressed on the account's normal-balance side (a balance is positive if it agrees with the normal side, negative otherwise); and (4) also verifies the accounting equation: total debits must equal total credits across all transactions. If they do not balance, raise a ValueError with the message 'Unbalanced ledger'. Example: accounts = [('5000', 'Office Supplies', 'debit'), ('2100', 'Accounts Payable', 'credit')], transactions = [('5000', 'paper', '25.505'), ('2100', 'invoice', '25.50')] \u2192 25.505 rounds to 25.51 (half-up), so the result is {'5000': Decimal('25.51'), '2100': Decimal('25.50')} and the ledger balances (debit 25.51, credit 25.50 differ but the check uses unrounded sums... note: in this example the unrounded debit is 25.505 and credit is 25.50, which are unequal, so this example would raise 'Unbalanced ledger'; use instead transactions [('5000','paper','25.50'), ('2100','invoice','25.50')] which returns {'5000': Decimal('25.50'), '2100': Decimal('25.50')})."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round_cents(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef trial_balance(accounts, transactions):\n normal = {}\n names = {}\n for code, name, side in accounts:\n normal[code] = side\n names[code] = name\n\n balances = {code: Decimal('0.00') for code in normal}\n\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n\n for code, description, amount_str in transactions:\n if code not in normal:\n raise ValueError(f\"Unknown account code: {code}\")\n\n amount = Decimal(amount_str)\n\n # Determine debit/credit side from the sign and the account's normal balance.\n if amount >= 0:\n if normal[code] == 'debit':\n debit = amount\n credit = Decimal('0')\n else:\n debit = Decimal('0')\n credit = amount\n else:\n if normal[code] == 'debit':\n debit = Decimal('0')\n credit = -amount\n else:\n debit = -amount\n credit = Decimal('0')\n\n total_debits += debit\n total_credits += credit\n\n # Apply on the account's normal-balance axis: positive = normal side.\n if normal[code] == 'debit':\n balances[code] += debit - credit\n else:\n balances[code] += credit - debit\n\n balances[code] = _round_cents(balances[code])\n\n if total_debits != total_credits:\n raise ValueError('Unbalanced ledger')\n\n return {code: _round_cents(bal) for code, bal in balances.items()}\n\n\nif __name__ == '__main__':\n accounts = [\n ('5000', 'Office Supplies', 'debit'),\n ('2100', 'Accounts Payable', 'credit'),\n ]\n transactions = [\n ('5000', 'paper', '25.50'),\n ('2100', 'invoice', '25.50'),\n ]\n result = trial_balance(accounts, transactions)\n print(result)\n assert result == {'5000': Decimal('25.50'), '2100': Decimal('25.50')}\n\n # Rounding example: each balance is rounded half-up to cents as applied.\n txns2 = [('5000', 'paper', '25.505'), ('2100', 'invoice', '25.505')]\n result2 = trial_balance(accounts, txns2)\n assert result2 == {'5000': Decimal('25.51'), '2100': Decimal('25.51')}\n\n # Unbalanced ledger must raise.\n try:\n trial_balance(accounts, [('5000', 'paper', '10.00'), ('2100', 'inv', '9.99')])\n raise AssertionError('expected ValueError')\n except ValueError as e:\n assert str(e) == 'Unbalanced ledger'\n\n # Unknown account must raise.\n try:\n trial_balance(accounts, [('9999', 'x', '1.00')])\n raise AssertionError('expected ValueError')\n except ValueError:\n pass\n\n print('All checks passed.')"}], "meta": {"idx": 2258, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1155, "latency_s": 14.0}} +{"prompt": [{"role": "user", "content": "Write a function `calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions)` that computes an employee's net pay for one payroll period. The gross pay and pre-tax deductions (such as health insurance premiums) are given as Decimal amounts, while federal_rate and state_rate are Decimal tax rates (e.g., Decimal('0.15') for 15%). Pre-tax deductions are subtracted from gross pay before taxes are computed; federal and state taxes are each applied to the taxable wages and rounded to the nearest cent using ROUND_HALF_UP. Net pay equals gross pay minus pre-tax deductions minus both taxes, also rounded to the nearest cent with ROUND_HALF_UP. Return a dict with keys 'federal_tax', 'state_tax', and 'net_pay' as Decimal values. For example, with gross_pay=Decimal('2500.00'), federal_rate=Decimal('0.15'), state_rate=Decimal('0.05'), and pre_tax_deductions=Decimal('200.00'), the taxable wages are 2300.00, federal_tax is 345.00, state_tax is 115.00, and net_pay is 1840.00. The solution must use only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions):\n gross_pay = Decimal(gross_pay)\n federal_rate = Decimal(federal_rate)\n state_rate = Decimal(state_rate)\n pre_tax_deductions = Decimal(pre_tax_deductions)\n\n cent = Decimal('0.01')\n\n taxable_wages = gross_pay - pre_tax_deductions\n\n federal_tax = (taxable_wages * federal_rate).quantize(cent, rounding=ROUND_HALF_UP)\n state_tax = (taxable_wages * state_rate).quantize(cent, rounding=ROUND_HALF_UP)\n\n net_pay = (gross_pay - pre_tax_deductions - federal_tax - state_tax).quantize(cent, rounding=ROUND_HALF_UP)\n\n return {\n 'federal_tax': federal_tax,\n 'state_tax': state_tax,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = calculate_net_pay(\n Decimal('2500.00'),\n Decimal('0.15'),\n Decimal('0.05'),\n Decimal('200.00'),\n )\n print(result)\n assert result['federal_tax'] == Decimal('345.00')\n assert result['state_tax'] == Decimal('115.00')\n assert result['net_pay'] == Decimal('1840.00')"}], "meta": {"idx": 2264, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 555, "latency_s": 4.0}} +{"prompt": [{"role": "user", "content": "A bookkeeper needs to generate an amortization ledger for a loan with simple annual interest applied monthly. Given a principal amount (as a string, e.g. '1200.00'), an annual nominal interest rate as a percentage (e.g. 5.5 meaning 5.5%), a loan term in months, and a fixed monthly payment (as a string, e.g. '102.50'), produce the ledger: for each month, compute interest as principal_balance * (rate/100/12), rounded half-up to cents; add it to the balance, subtract the payment (final payment may be smaller to zero the balance), and record the entry. The function must use Decimal arithmetic throughout, never float. Return a list of tuples (month, interest, payment, ending_balance) plus the total interest paid. If a fixed payment does not fully pay off the loan within the term (i.e., balance remains > 0 after 'months' entries), raise ValueError. Example: principal '1000.00', rate 12.0, months 12, payment '88.85' -> first month interest is '10.00', ending balance '921.15'; the loan pays off with total interest '64.81' (12 entries, last payment '79.97'). Write a function amortize(principal, annual_rate_pct, months, payment) that returns (entries, total_interest)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortize(principal, annual_rate_pct, months, payment):\n balance = Decimal(principal).quantize(CENT)\n pay = Decimal(payment).quantize(CENT)\n monthly_rate = Decimal(str(annual_rate_pct)) / Decimal(100) / Decimal(12)\n entries = []\n total_interest = Decimal('0.00')\n\n for month in range(1, months + 1):\n if balance <= 0:\n break\n interest = _round_cents(balance * monthly_rate)\n balance = _round_cents(balance + interest)\n actual_pay = min(pay, balance)\n balance = _round_cents(balance - actual_pay)\n total_interest = _round_cents(total_interest + interest)\n entries.append((month, interest, actual_pay, balance))\n\n if balance > 0:\n raise ValueError('Payment does not amortize the loan within the term')\n\n return entries, total_interest\n\n\nif __name__ == '__main__':\n entries, total_interest = amortize('1000.00', 12.0, 12, '88.85')\n assert entries[0] == (1, Decimal('10.00'), Decimal('88.85'), Decimal('921.15'))\n assert entries[-1] == (12, Decimal('0.80'), Decimal('79.97'), Decimal('0.00'))\n assert total_interest == Decimal('64.81')\n print(entries)\n print('Total interest:', total_interest)"}], "meta": {"idx": 2257, "topic": "interest calculation and payment schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 650, "latency_s": 21.4}} +{"prompt": [{"role": "user", "content": "Implement a small ledger system using dataclasses and Decimal arithmetic. Define a dataclass `LedgerEntry` with fields: `date` (str, ISO format), `description` (str), `debits` (dict mapping account name to Decimal amount), `credits` (dict mapping account name to Decimal amount), and `id` (int, auto-incremented starting at 1 via a class-level counter). A valid entry must balance: total debits must equal total credits; raise `ValueError` if not. Implement class `Ledger` with methods: `add_entry(entry)` that stores the entry, `balance(account)` returning the net balance of an account as a Decimal (debits increase, credits decrease; accounts not seen return Decimal('0.00')), and `trial_balance()` returning a dict mapping each account to its balance, with all amounts quantized to 2 decimal places using ROUND_HALF_UP. Monetary amounts must be parsed with `Decimal` from strings. Example: adding an entry with date '2024-01-05', description 'Buy supplies', debits {'Supplies': '120.50'}, credits {'Cash': '120.50'} then calling `balance('Supplies')` returns Decimal('120.50'), `balance('Cash')` returns Decimal('-120.50'), and `balance('Equity')` returns Decimal('0.00'). An entry with debits {'Supplies': '10.00'} and credits {'Cash': '9.00'} must raise ValueError."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Dict\n\nTWO = Decimal('0.01')\n\n\ndef _to_money(value):\n if isinstance(value, Decimal):\n d = value\n else:\n d = Decimal(str(value))\n if d.is_nan() or d.is_infinite():\n raise ValueError(f\"Invalid monetary amount: {value!r}\")\n return d\n\n\n@dataclass\nclass LedgerEntry:\n date: str\n description: str\n debits: Dict[str, Decimal]\n credits: Dict[str, Decimal]\n id: int = field(default=0)\n\n _counter: int = 0\n\n def __post_init__(self):\n self.debits = {a: _to_money(v) for a, v in self.debits.items()}\n self.credits = {a: _to_money(v) for a, v in self.credits.items()}\n if any(v < 0 for v in self.debits.values()) or any(v < 0 for v in self.credits.values()):\n raise ValueError(\"Amounts must be non-negative\")\n if sum(self.debits.values()) != sum(self.credits.values()):\n raise ValueError(\"Entry is not balanced: total debits must equal total credits\")\n type(self)._counter += 1\n self.id = type(self)._counter\n\n @classmethod\n def reset_counter(cls):\n cls._counter = 0\n\n\nclass Ledger:\n def __init__(self):\n self._entries = []\n\n def add_entry(self, entry):\n if not isinstance(entry, LedgerEntry):\n raise TypeError(\"Expected a LedgerEntry\")\n self._entries.append(entry)\n\n def balance(self, account):\n total = Decimal('0')\n for e in self._entries:\n total += e.debits.get(account, Decimal('0'))\n total -= e.credits.get(account, Decimal('0'))\n return total.quantize(TWO, rounding=ROUND_HALF_UP)\n\n def trial_balance(self):\n accounts = set()\n for e in self._entries:\n accounts.update(e.debits.keys())\n accounts.update(e.credits.keys())\n return {a: self.balance(a) for a in sorted(accounts)}\n\n\nif __name__ == \"__main__\":\n ledger = Ledger()\n ledger.add_entry(LedgerEntry('2024-01-05', 'Buy supplies',\n {'Supplies': '120.50'}, {'Cash': '120.50'}))\n assert ledger.balance('Supplies') == Decimal('120.50')\n assert ledger.balance('Cash') == Decimal('-120.50')\n assert ledger.balance('Equity') == Decimal('0.00')\n try:\n LedgerEntry('2024-01-06', 'Bad', {'Supplies': '10.00'}, {'Cash': '9.00'})\n raise AssertionError(\"expected ValueError\")\n except ValueError:\n pass\n print(ledger.trial_balance())\n print(\"All checks passed.\")"}], "meta": {"idx": 2266, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 985, "latency_s": 7.3}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, life, method, rate=None)` that produces a depreciation ledger for a fixed asset. `cost` and `salvage` are Decimal amounts, `life` is an integer number of years, and `method` is either 'straight-line' or 'declining-balance'. For straight-line, each year's depreciation is (cost - salvage) / life, rounded to cents with ROUND_HALF_UP, with a final adjusting entry in the last year so the accumulated depreciation exactly equals cost - salvage. For declining-balance, each year's depreciation is the prior book value multiplied by the given `rate` (a Decimal, required for this method), rounded to cents, but depreciation is capped so the asset's book value never falls below salvage; once book value would reach salvage, remaining depreciation is zero. The function must raise ValueError if life < 1, if salvage > cost, or if method is 'declining-balance' and rate is not between 0 and 1. Return a list of dictionaries with keys 'year', 'depreciation', 'accumulated', 'book_value' (all monetary values as Decimal quantized to 2 places). Example: cost=Decimal('10000.00'), salvage=Decimal('1000.00'), life=5, method='straight-line' yields yearly depreciation of 1800.00 for years 1-4 and 2800.00 in year 5, with final book value 1000.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef depreciation_schedule(cost, salvage, life, method, rate=None):\n cost = Decimal(cost)\n salvage = Decimal(salvage)\n if life < 1:\n raise ValueError('life must be at least 1')\n if salvage > cost:\n raise ValueError('salvage must not exceed cost')\n method = method.lower()\n if method not in ('straight-line', 'declining-balance'):\n raise ValueError('unknown method: ' + str(method))\n if method == 'declining-balance':\n if rate is None:\n raise ValueError('rate is required for declining-balance')\n rate = Decimal(rate)\n if not (Decimal('0') < rate < Decimal('1')):\n raise ValueError('rate must be between 0 and 1')\n\n cents = Decimal('0.01')\n\n def q(x):\n return x.quantize(cents, rounding=ROUND_HALF_UP)\n\n entries = []\n accumulated = Decimal('0.00')\n book_value = cost\n total_depreciable = cost - salvage\n\n if method == 'straight-line':\n base = q(total_depreciable / Decimal(life))\n for year in range(1, life + 1):\n if year < life:\n dep = base\n else:\n dep = q(total_depreciable - accumulated)\n accumulated = q(accumulated + dep)\n book_value = q(cost - accumulated)\n entries.append({\n 'year': year,\n 'depreciation': dep,\n 'accumulated': accumulated,\n 'book_value': book_value,\n })\n else:\n for year in range(1, life + 1):\n raw = book_value * rate\n dep = q(raw)\n remaining = q(book_value - salvage)\n if dep > remaining:\n dep = remaining\n if dep < Decimal('0.00'):\n dep = Decimal('0.00')\n accumulated = q(accumulated + dep)\n book_value = q(cost - accumulated)\n entries.append({\n 'year': year,\n 'depreciation': dep,\n 'accumulated': accumulated,\n 'book_value': book_value,\n })\n\n return entries\n\n\nif __name__ == '__main__':\n from decimal import Decimal as D\n for e in depreciation_schedule(D('10000.00'), D('1000.00'), 5, 'straight-line'):\n print(e)\n print()\n for e in depreciation_schedule(D('10000.00'), D('1000.00'), 5, 'declining-balance', rate=D('0.40')):\n print(e)"}], "meta": {"idx": 2263, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 952, "latency_s": 15.4}} +{"prompt": [{"role": "user", "content": "Write a function `summarize_ledger(entries)` that takes a list of ledger entries and produces a Profit & Loss summary and a Balance Sheet summary. Each entry is a dict with keys: 'date' (ISO string), 'account' (string, dot-separated hierarchy like 'asset.cash' or 'revenue.sales'), and 'amount' (Decimal, positive for debits, negative for credits \u2014 for this task simply treat 'asset' and 'expense' prefixed accounts as debit-normal and 'liability', 'equity', and 'revenue' prefixed accounts as credit-normal). Compute: (1) P&L: total revenue, total expense, and net profit = revenue - expense, where each account's total is its absolute balance; (2) Balance Sheet: total assets, total liabilities, total equity, and a check that assets == liabilities + equity + net_profit, all rounded to 2 decimal places with ROUND_HALF_UP. Return a dict with keys 'revenue', 'expense', 'net_profit', 'assets', 'liabilities', 'equity', 'balanced' (a bool for the check, comparing the rounded values). Example: entries = [{'date':'2024-01-05','account':'asset.cash','amount':Decimal('1000.00')}, {'date':'2024-01-05','account':'equity.capital','amount':Decimal('-1000.00')}, {'date':'2024-01-10','account':'revenue.sales','amount':Decimal('-250.505')}, {'date':'2024-01-10','account':'asset.cash','amount':Decimal('250.505')}] yields revenue=Decimal('250.51'), expense=Decimal('0.00'), net_profit=Decimal('250.51'), assets=Decimal('1250.51'), liabilities=Decimal('0.00'), equity=Decimal('1000.00'), balanced=True."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize_ledger(entries):\n CENT = Decimal('0.01')\n\n def r2(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n balances = {}\n for e in entries:\n acct = e['account']\n balances[acct] = balances.get(acct, Decimal('0')) + e['amount']\n\n revenue = Decimal('0')\n expense = Decimal('0')\n assets = Decimal('0')\n liabilities = Decimal('0')\n equity = Decimal('0')\n\n for acct, bal in balances.items():\n top = acct.split('.')[0]\n if top == 'revenue':\n revenue += abs(bal)\n elif top == 'expense':\n expense += abs(bal)\n elif top == 'asset':\n assets += bal\n elif top == 'liability':\n liabilities += abs(bal)\n elif top == 'equity':\n equity += abs(bal)\n\n net_profit = revenue - expense\n\n result = {\n 'revenue': r2(revenue),\n 'expense': r2(expense),\n 'net_profit': r2(net_profit),\n 'assets': r2(assets),\n 'liabilities': r2(liabilities),\n 'equity': r2(equity),\n }\n result['balanced'] = (\n result['assets']\n == result['liabilities'] + result['equity'] + result['net_profit']\n )\n return result\n\n\nif __name__ == '__main__':\n entries = [\n {'date': '2024-01-05', 'account': 'asset.cash', 'amount': Decimal('1000.00')},\n {'date': '2024-01-05', 'account': 'equity.capital', 'amount': Decimal('-1000.00')},\n {'date': '2024-01-10', 'account': 'revenue.sales', 'amount': Decimal('-250.505')},\n {'date': '2024-01-10', 'account': 'asset.cash', 'amount': Decimal('250.505')},\n ]\n print(summarize_ledger(entries))"}], "meta": {"idx": 2265, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 820, "latency_s": 11.6}} +{"prompt": [{"role": "user", "content": "Write a function `calculate_net_pay(gross_pay, federal_rate, state_rate, social_security_rate, medicare_rate, pre_tax_deduction)` that computes an employee's net pay from their gross pay. First subtract the pre-tax deduction (e.g., a health insurance premium) from the gross pay to get the taxable wages, floored at zero. Then apply each withholding rate (federal tax, state tax, Social Security, Medicare) to the taxable wages. Net pay equals gross pay minus the pre-tax deduction minus all four withholdings. All money amounts must be handled as Decimal values, and every computed money amount must be rounded to exactly 2 decimal places using ROUND_HALF_UP. Return a dict with keys 'taxable_wages', 'federal_tax', 'state_tax', 'social_security', 'medicare', 'total_withholdings', and 'net_pay', each a Decimal rounded to 2 places. Example: gross_pay = Decimal('3000.00'), federal_rate = Decimal('0.12'), state_rate = Decimal('0.05'), social_security_rate = Decimal('0.062'), medicare_rate = Decimal('0.0145'), pre_tax_deduction = Decimal('150.00') gives taxable_wages = Decimal('2850.00'), federal_tax = Decimal('342.00'), state_tax = Decimal('142.50'), social_security = Decimal('176.70'), medicare = Decimal('41.33') (2850 * 0.0145 = 41.325 rounds to 41.33), total_withholdings = Decimal('702.53'), and net_pay = Decimal('2147.47')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _money(value):\n \"\"\"Round a Decimal to 2 places, ROUND_HALF_UP.\"\"\"\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef calculate_net_pay(gross_pay, federal_rate, state_rate,\n social_security_rate, medicare_rate, pre_tax_deduction):\n gross_pay = Decimal(str(gross_pay))\n pre_tax_deduction = Decimal(str(pre_tax_deduction))\n\n taxable_wages = gross_pay - pre_tax_deduction\n if taxable_wages < 0:\n taxable_wages = Decimal('0.00')\n taxable_wages = _money(taxable_wages)\n\n federal_tax = _money(taxable_wages * Decimal(str(federal_rate)))\n state_tax = _money(taxable_wages * Decimal(str(state_rate)))\n social_security = _money(taxable_wages * Decimal(str(social_security_rate)))\n medicare = _money(taxable_wages * Decimal(str(medicare_rate)))\n\n total_withholdings = federal_tax + state_tax + social_security + medicare\n net_pay = _money(gross_pay - pre_tax_deduction - total_withholdings)\n\n return {\n 'taxable_wages': taxable_wages,\n 'federal_tax': federal_tax,\n 'state_tax': state_tax,\n 'social_security': social_security,\n 'medicare': medicare,\n 'total_withholdings': _money(total_withholdings),\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = calculate_net_pay(\n Decimal('3000.00'), Decimal('0.12'), Decimal('0.05'),\n Decimal('0.062'), Decimal('0.0145'), Decimal('150.00')\n )\n for key, value in result.items():\n print(f\"{key}: {value}\")"}], "meta": {"idx": 2269, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 748, "latency_s": 5.0}} +{"prompt": [{"role": "user", "content": "You are maintaining an inventory ledger for a single stock item. Given a list of transactions in chronological order, where each transaction is a tuple (kind, quantity, unit_price) with kind being 'IN' (a purchase) or 'OUT' (a sale), compute the ending inventory value under three costing methods: FIFO, LIFO, and weighted average. All money must be handled with Decimal and rounded to 2 decimal places with ROUND_HALF_UP at the end. For the weighted average method, the unit cost after each purchase is the total value of units on hand divided by the number of units on hand, and sales remove units at that average cost. For FIFO and LIFO, use layers of (quantity, unit_price); FIFO removes from the oldest layer first, LIFO from the newest layer first. Assume sales never exceed units on hand and quantities are positive integers. Input: a list of tuples like [('IN', 10, Decimal('2.00')), ('OUT', 4, None), ('IN', 5, Decimal('3.00')), ('OUT', 6, None)]. Output: a dict {'FIFO': Decimal, 'LIFO': Decimal, 'AVG': Decimal} giving the ending inventory value under each method. Worked example: for the input above, FIFO = 4*2.00 + 5*3.00 = Decimal('23.00'), LIFO = 6*2.00 + 3*3.00 = Decimal('21.00'), and AVG: after first IN avg=2.00, sell 4 leaves 6 units at 2.00=12.00, then buy 5 at 3.00 gives 11 units worth 27.00, avg=27.00/11; sell 6 leaves 5 units worth 5*27.00/11 = Decimal('12.27') when rounded."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef inventory_value(transactions):\n # FIFO\n fifo_layers = [] # list of [qty, price]\n for kind, qty, price in transactions:\n if kind == 'IN':\n fifo_layers.append([qty, price])\n else:\n remaining = qty\n while remaining > 0:\n layer = fifo_layers[0]\n take = min(remaining, layer[0])\n layer[0] -= take\n remaining -= take\n if layer[0] == 0:\n fifo_layers.pop(0)\n fifo_value = sum((q * p for q, p in fifo_layers), Decimal('0'))\n\n # LIFO\n lifo_layers = []\n for kind, qty, price in transactions:\n if kind == 'IN':\n lifo_layers.append([qty, price])\n else:\n remaining = qty\n while remaining > 0:\n layer = lifo_layers[-1]\n take = min(remaining, layer[0])\n layer[0] -= take\n remaining -= take\n if layer[0] == 0:\n lifo_layers.pop()\n lifo_value = sum((q * p for q, p in lifo_layers), Decimal('0'))\n\n # Weighted average\n qty_on_hand = 0\n total_value = Decimal('0')\n for kind, qty, price in transactions:\n if kind == 'IN':\n qty_on_hand += qty\n total_value += qty * price\n else:\n avg_cost = total_value / qty_on_hand\n qty_on_hand -= qty\n total_value = avg_cost * qty_on_hand\n avg_value = total_value\n\n q = Decimal('0.01')\n return {\n 'FIFO': fifo_value.quantize(q, rounding=ROUND_HALF_UP),\n 'LIFO': lifo_value.quantize(q, rounding=ROUND_HALF_UP),\n 'AVG': avg_value.quantize(q, rounding=ROUND_HALF_UP),\n }\n\n\nif __name__ == '__main__':\n txns = [\n ('IN', 10, Decimal('2.00')),\n ('OUT', 4, None),\n ('IN', 5, Decimal('3.00')),\n ('OUT', 6, None),\n ]\n print(inventory_value(txns))"}], "meta": {"idx": 2268, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "novita", "in_tokens": 204, "out_tokens": 968, "latency_s": 12.3}} +{"prompt": [{"role": "user", "content": "You are maintaining a loan ledger for a small credit union. A fixed-rate loan of principal P (a Decimal, in dollars) is repaid over N equal monthly payments, with an annual nominal interest rate of r percent compounded monthly. Each month, interest is computed on the outstanding balance as balance * (r/100/12), rounded to cents (ROUND_HALF_UP). The monthly payment is computed as the standard annuity payment P * i / (1 - (1+i)**-N) where i = r/100/12, also rounded to cents (ROUND_HALF_UP); in the final month, the payment is adjusted down so the balance reaches exactly zero. Write a function amortize(principal, annual_rate_percent, months) that returns a list of ledger entries, each a dict {'month': int, 'payment': Decimal, 'interest': Decimal, 'principal': Decimal, 'balance': Decimal} rounded to cents. For example, amortize(Decimal('1000'), Decimal('5'), 12) yields a first entry with interest Decimal('4.17'), principal Decimal('81.44'), payment Decimal('85.61'), balance Decimal('918.56'), and the final entry has balance Decimal('0.00') with the last payment adjusted so the loan closes exactly."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _round(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortize(principal, annual_rate_percent, months):\n p = Decimal(str(principal))\n r = Decimal(str(annual_rate_percent))\n n = int(months)\n i = r / Decimal('100') / Decimal('12')\n if i == 0:\n base_payment = _round(p / Decimal(n))\n else:\n base_payment = _round(p * i / (Decimal(1) - (Decimal(1) + i) ** (-n)))\n entries = []\n balance = p\n for month in range(1, n + 1):\n interest = _round(balance * i)\n if month == n:\n payment = balance + interest\n else:\n payment = base_payment\n principal_part = payment - interest\n balance = balance - principal_part\n if month == n:\n payment = _round(payment)\n principal_part = payment - interest\n balance = Decimal('0.00')\n entries.append({\n 'month': month,\n 'payment': _round(payment),\n 'interest': interest,\n 'principal': _round(principal_part),\n 'balance': _round(balance),\n })\n return entries\n\nif __name__ == '__main__':\n for e in amortize(Decimal('1000'), Decimal('5'), 12):\n print(e)"}], "meta": {"idx": 2267, "topic": "loan and mortgage amortization schedules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 615, "latency_s": 26.2}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts as a list of account names (each like 'Expenses:Office:Supplies') and a list of expense transactions, each a tuple (date, description, account, amount_string). Write a function `categorize_expenses(chart, transactions)` that validates every transaction: the account must exist in the chart and the amount must be a valid monetary string (decimal number, at most 2 decimal places, non-negative). Invalid transactions are collected into a report. For valid ones, return a per-account total of expenses using Decimal arithmetic, with amounts rounded to 2 decimal places via ROUND_HALF_UP, sorted by account name. Return a dict {'totals': [(account, Decimal), ...], 'invalid': [(description, reason), ...]}. Example: chart = ['Expenses:Office:Supplies', 'Expenses:Travel:Flights']; transactions = [('2024-01-05', 'Paper', 'Expenses:Office:Supplies', '12.345'), ('2024-01-06', 'Taxi', 'Expenses:Travel:Flights', '25.50'), ('2024-01-07', 'Hotel', 'Expenses:Travel:Rooms', '100.00')]. Output: {'totals': [('Expenses:Travel:Flights', Decimal('25.50'))], 'invalid': [('Paper', 'amount has more than 2 decimal places'), ('Hotel', 'unknown account')]}. The order of 'invalid' entries must match the input transaction order."}], "completion": [{"role": "assistant", "content": "import re\nfrom decimal import Decimal, ROUND_HALF_UP\n\n\ndef categorize_expenses(chart, transactions):\n accounts = set(chart)\n cents_re = re.compile(r'^\\d+(\\.\\d{1,2})?$')\n totals = {}\n invalid = []\n\n for date, description, account, amount_str in transactions:\n if account not in accounts:\n invalid.append((description, 'unknown account'))\n continue\n if not isinstance(amount_str, str) or not cents_re.match(amount_str):\n invalid.append((description, 'amount has more than 2 decimal places'))\n continue\n amount = Decimal(amount_str)\n totals[account] = totals.get(account, Decimal('0')) + amount\n\n rounded_totals = [\n (acc, totals[acc].quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))\n for acc in sorted(totals)\n ]\n return {'totals': rounded_totals, 'invalid': invalid}\n\n\nif __name__ == '__main__':\n chart = ['Expenses:Office:Supplies', 'Expenses:Travel:Flights']\n transactions = [\n ('2024-01-05', 'Paper', 'Expenses:Office:Supplies', '12.345'),\n ('2024-01-06', 'Taxi', 'Expenses:Travel:Flights', '25.50'),\n ('2024-01-07', 'Hotel', 'Expenses:Travel:Rooms', '100.00'),\n ]\n print(categorize_expenses(chart, transactions))"}], "meta": {"idx": 2273, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 644, "latency_s": 5.9}} +{"prompt": [{"role": "user", "content": "Design a double-entry ledger system using dataclasses and Decimal arithmetic. Define a dataclass `Entry` with fields: `date` (str, ISO format), `description` (str), and `amount` (Decimal, positive for debit, negative for credit), plus a dataclass `Account` with fields: `name` (str) and `entries` (list of Entry, default empty). Implement a class `Ledger` with methods: `post(account_name, entry)` that appends the entry (creating the account if needed), `balance(account_name)` that returns the sum of amounts rounded to 2 decimal places with ROUND_HALF_UP (raising KeyError for unknown accounts), and `trial_balance()` that returns a dict mapping each account name to its rounded balance. All postings across all accounts must sum to exactly zero; implement `is_balanced()` returning True if the total of all entries equals Decimal('0.00'). Example: posting entries [('2024-01-01','Cash sale',Decimal('120.00'))] to 'Cash' and [('2024-01-01','Cash sale',Decimal('-120.00'))] to 'Revenue' must yield balance('Cash') == Decimal('120.00'), balance('Revenue') == Decimal('-120.00'), and is_balanced() == True."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import List, Dict\n\n\n@dataclass\nclass Entry:\n date: str\n description: str\n amount: Decimal\n\n\n@dataclass\nclass Account:\n name: str\n entries: List[Entry] = field(default_factory=list)\n\n\nclass Ledger:\n def __init__(self):\n self.accounts: Dict[str, Account] = {}\n\n def post(self, account_name: str, entry: Entry) -> None:\n if account_name not in self.accounts:\n self.accounts[account_name] = Account(name=account_name)\n self.accounts[account_name].entries.append(entry)\n\n @staticmethod\n def _round(value: Decimal) -> Decimal:\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n def balance(self, account_name: str) -> Decimal:\n if account_name not in self.accounts:\n raise KeyError(f\"Unknown account: {account_name}\")\n total = sum((e.amount for e in self.accounts[account_name].entries),\n Decimal('0'))\n return self._round(total)\n\n def trial_balance(self) -> Dict[str, Decimal]:\n return {name: self.balance(name) for name in self.accounts}\n\n def is_balanced(self) -> bool:\n total = sum((e.amount for acc in self.accounts.values()\n for e in acc.entries), Decimal('0'))\n return self._round(total) == Decimal('0.00')\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.post('Cash', Entry('2024-01-01', 'Cash sale', Decimal('120.00')))\n ledger.post('Revenue', Entry('2024-01-01', 'Cash sale', Decimal('-120.00')))\n assert ledger.balance('Cash') == Decimal('120.00')\n assert ledger.balance('Revenue') == Decimal('-120.00')\n assert ledger.is_balanced() is True\n assert ledger.trial_balance() == {'Cash': Decimal('120.00'),\n 'Revenue': Decimal('-120.00')}\n print('All checks passed.')"}], "meta": {"idx": 2275, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 777, "latency_s": 7.7}} +{"prompt": [{"role": "user", "content": "Implement `process_journal(operations)` for a double-entry bookkeeping system that supports correcting, reversing, and voiding journal entries using exact `Decimal` arithmetic. Each operation is a tuple: `(\"POST\", entry_id, lines)` where `lines` is a list of `(account, amount_string)` pairs (debits positive, credits negative); `(\"REVERSE\", entry_id)` which attaches a mirror entry with every amount negated so the pair nets to zero but stays in the audit trail; `(\"VOID\", entry_id)` which removes the entry's effect entirely as if it never happened; and `(\"CORRECT\", entry_id, new_lines)` which replaces the entry's lines retroactively. Validation rules (violations append `\": \"` to an errors list and the operation is rejected): POST requires a fresh id, every amount nonzero with at most 2 decimal places, and the lines summing to exactly zero (\"unbalanced\"); VOID fails on unknown ids, already-voided entries, or reversed entries; REVERSE fails on unknown, voided, or already-reversed entries; CORRECT fails on unknown, voided, or reversed entries (a reversal mirrors the original amounts, so the original may no longer be edited) and the new lines must pass the same balance/scale checks as POST. The function returns a tuple `(balances, errors)` where `balances` maps every account appearing in any non-voided entry (reversal mirrors included) to its net `Decimal` balance, and `errors` lists rejection messages in order. Worked example: for ops = [(\"POST\",\"E1\",[(\"Cash\",\"120.00\"),(\"Revenue\",\"-120.00\")]), (\"POST\",\"E2\",[(\"AR\",\"75.50\"),(\"Revenue\",\"-75.50\")]), (\"REVERSE\",\"E1\"), (\"VOID\",\"E2\"), (\"POST\",\"E3\",[(\"Cash\",\"40.25\"),(\"Revenue\",\"-40.25\")]), (\"CORRECT\",\"E3\",[(\"Cash\",\"40.75\"),(\"Revenue\",\"-40.75\")])], the result is ({'Cash': Decimal('40.75'), 'Revenue': Decimal('-40.75')}, []) \u2014 E1 nets to zero via its reversal, E2 is voided so AR never appears, and E3's correction retroactively changes its amounts."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef _validate_lines(lines):\n \"\"\"Return (parsed_lines, None) if valid, else (None, reason).\"\"\"\n if not lines:\n return None, \"no_lines\"\n parsed = []\n total = Decimal(\"0\")\n for account, amount_str in lines:\n try:\n amount = Decimal(str(amount_str))\n except Exception:\n return None, \"bad_amount\"\n if not amount.is_finite():\n return None, \"bad_amount\"\n # At most 2 decimal places (cents precision).\n exponent = amount.as_tuple().exponent\n if not isinstance(exponent, int) or -exponent > 2:\n return None, \"scale\"\n if amount == 0:\n return None, \"zero_amount\"\n parsed.append((account, amount))\n total += amount\n if total != 0:\n return None, \"unbalanced\"\n return parsed, None\n\n\ndef process_journal(operations):\n \"\"\"\n Process bookkeeping operations supporting POST, REVERSE, VOID, CORRECT.\n\n Returns (balances, errors) where balances maps each account appearing in\n any non-voided entry to its net Decimal balance, and errors is a list of\n \": \" strings for rejected operations.\n \"\"\"\n entries = {} # entry_id -> {\"lines\": [...], \"voided\": bool, \"reversed\": bool}\n errors = []\n\n for idx, op in enumerate(operations):\n kind = op[0]\n\n if kind == \"POST\":\n _, entry_id, lines = op\n if entry_id in entries:\n errors.append(\"%d: duplicate_id\" % idx)\n continue\n parsed, reason = _validate_lines(lines)\n if parsed is None:\n errors.append(\"%d: %s\" % (idx, reason))\n continue\n entries[entry_id] = {\n \"lines\": parsed,\n \"voided\": False,\n \"reversed\": False,\n }\n\n elif kind == \"VOID\":\n _, entry_id = op\n entry = entries.get(entry_id)\n if entry is None:\n errors.append(\"%d: unknown_id\" % idx)\n elif entry[\"voided\"]:\n errors.append(\"%d: already_voided\" % idx)\n elif entry[\"reversed\"]:\n errors.append(\"%d: cannot_void_reversed\" % idx)\n else:\n entry[\"voided\"] = True\n\n elif kind == \"REVERSE\":\n _, entry_id = op\n entry = entries.get(entry_id)\n if entry is None:\n errors.append(\"%d: unknown_id\" % idx)\n elif entry[\"voided\"]:\n errors.append(\"%d: cannot_reverse_voided\" % idx)\n elif entry[\"reversed\"]:\n errors.append(\"%d: already_reversed\" % idx)\n else:\n entry[\"reversed\"] = True\n\n elif kind == \"CORRECT\":\n _, entry_id, new_lines = op\n entry = entries.get(entry_id)\n if entry is None:\n errors.append(\"%d: unknown_id\" % idx)\n elif entry[\"voided\"]:\n errors.append(\"%d: cannot_correct_voided\" % idx)\n elif entry[\"reversed\"]:\n errors.append(\"%d: cannot_correct_reversed\" % idx)\n else:\n parsed, reason = _validate_lines(new_lines)\n if parsed is None:\n errors.append(\"%d: %s\" % (idx, reason))\n else:\n entry[\"lines\"] = parsed\n\n else:\n errors.append(\"%d: unknown_operation\" % idx)\n\n # Compute balances over all non-voided entries. A reversed entry\n # contributes its original lines plus a negated mirror, netting to zero\n # while keeping its accounts visible in the report.\n balances = {}\n for entry in entries.values():\n if entry[\"voided\"]:\n continue\n contributions = list(entry[\"lines\"])\n if entry[\"reversed\"]:\n contributions.extend(\n (account, -amount) for account, amount in entry[\"lines\"]\n )\n for account, amount in contributions:\n balances[account] = balances.get(account, Decimal(\"0\")) + amount\n\n return dict(sorted(balances.items())), errors\n\n\nif __name__ == \"__main__\":\n ops = [\n (\"POST\", \"E1\", [(\"Cash\", \"120.00\"), (\"Revenue\", \"-120.00\")]),\n (\"POST\", \"E2\", [(\"AR\", \"75.50\"), (\"Revenue\", \"-75.50\")]),\n (\"REVERSE\", \"E1\"),\n (\"VOID\", \"E2\"),\n (\"POST\", \"E3\", [(\"Cash\", \"40.25\"), (\"Revenue\", \"-40.25\")]),\n (\"CORRECT\", \"E3\", [(\"Cash\", \"40.75\"), (\"Revenue\", \"-40.75\")]),\n ]\n balances, errors = process_journal(ops)\n assert balances == {\"Cash\": Decimal(\"40.75\"), \"Revenue\": Decimal(\"-40.75\")}\n assert errors == []\n print(balances)\n print(errors)"}], "meta": {"idx": 2271, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1755, "latency_s": 27.7}} +{"prompt": [{"role": "user", "content": "Implement an accounting module (standard library only, using `decimal.Decimal` for all money math) containing three public pieces: (1) `accrue_interest(principal, annual_rate, days, basis=365)` returning interest rounded to 2 decimal places with banker's rounding (ROUND_HALF_EVEN), raising `ValueError` for negative `principal`, negative `days`, or non-positive `basis`; (2) `allocate(amount, weights)` splitting a cents-exact `amount` across non-negative `weights` (not all zero, list non-empty) proportionally using the largest-remainder method so the parts sum exactly to `amount`, raising `ValueError` on bad weights; (3) a `Ledger` class with `post(entry_id, lines)`, `balance(account)`, and `trial_balance()`, where `lines` maps account names to signed `Decimal` amounts (debit positive, credit negative), `post` raises `DuplicateEntryError` on a reused `entry_id`, `UnbalancedEntryError` if the lines do not sum to exactly zero, and `TypeError` if any amount is a `float`. For example, `accrue_interest(Decimal('1000.00'), Decimal('0.05'), 31)` returns `Decimal('4.25')` because 1550/365 = 4.24657... rounds up, while `accrue_interest(Decimal('1250'), Decimal('0.0365'), 1)` returns `Decimal('0.12')` because 0.125 rounds to even; and `allocate(Decimal('0.10'), [Decimal('1'), Decimal('1'), Decimal('1')])` must return `[Decimal('0.04'), Decimal('0.03'), Decimal('0.03')]` (ties in the remainder go to the earliest index). Then write a comprehensive `unittest` test suite (at least 12 tests) that verifies every rule above, including the exact worked examples, a ROUND_HALF_EVEN tie pair (0.125 -> 0.12 and 0.135 -> 0.14), negative-amount allocation, error cases for each exception type, and that a posted entry's lines cannot unbalance the ledger afterwards. The final program must run the suite when executed and print a passing test result."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom decimal import Decimal, ROUND_HALF_EVEN, ROUND_FLOOR\n\nCENT = Decimal('0.01')\n\n\nclass UnbalancedEntryError(Exception):\n \"\"\"Raised when a journal entry's lines do not sum to exactly zero.\"\"\"\n\n\nclass DuplicateEntryError(Exception):\n \"\"\"Raised when an entry_id is posted to a ledger more than once.\"\"\"\n\n\ndef accrue_interest(principal, annual_rate, days, basis=365):\n if not isinstance(principal, Decimal) or not isinstance(annual_rate, Decimal):\n raise TypeError('principal and annual_rate must be Decimal')\n if days < 0:\n raise ValueError('days must be non-negative')\n if basis <= 0:\n raise ValueError('basis must be positive')\n if principal < 0:\n raise ValueError('principal must be non-negative')\n raw = principal * annual_rate * days / Decimal(basis)\n return raw.quantize(CENT, rounding=ROUND_HALF_EVEN)\n\n\ndef allocate(amount, weights):\n if not isinstance(amount, Decimal):\n raise TypeError('amount must be Decimal')\n if not isinstance(weights, (list, tuple)) or len(weights) == 0:\n raise ValueError('weights must be a non-empty list')\n for w in weights:\n if not isinstance(w, Decimal):\n raise TypeError('each weight must be Decimal')\n if w < 0:\n raise ValueError('weights must be non-negative')\n total_weight = sum(weights, Decimal('0'))\n if total_weight == 0:\n raise ValueError('weights must not all be zero')\n\n cents = amount.quantize(CENT, rounding=ROUND_HALF_EVEN)\n exact = [(cents * w) / total_weight for w in weights]\n floors = [e.quantize(CENT, rounding=ROUND_FLOOR) for e in exact]\n diff = cents - sum(floors, Decimal('0'))\n step = Decimal('0.01')\n n = int(abs(diff) / step)\n sign = 1 if diff > 0 else -1\n # Largest remainder first; ties broken by earliest index.\n order = sorted(range(len(weights)),\n key=lambda i: (exact[i] - floors[i], -i),\n reverse=True)\n parts = list(floors)\n for i in order[:n]:\n parts[i] += sign * step\n assert sum(parts, Decimal('0')) == cents\n return parts\n\n\nclass Ledger:\n def __init__(self):\n self._entries = {}\n\n def post(self, entry_id, lines):\n if entry_id in self._entries:\n raise DuplicateEntryError('entry_id %r already posted' % (entry_id,))\n if not isinstance(lines, dict) or not lines:\n raise ValueError('lines must be a non-empty dict')\n checked = []\n for account, amount in lines.items():\n if not isinstance(account, str) or not account:\n raise ValueError('account names must be non-empty strings')\n if isinstance(amount, float):\n raise TypeError('float amounts are forbidden; use Decimal')\n if not isinstance(amount, Decimal):\n raise TypeError('amounts must be Decimal')\n checked.append((account, amount))\n if sum((a for _, a in checked), Decimal('0')) != Decimal('0'):\n raise UnbalancedEntryError('entry lines do not balance to zero')\n # Store an immutable snapshot so caller cannot mutate posted lines.\n self._entries[entry_id] = tuple(sorted(checked))\n\n def balance(self, account):\n return sum((amt for entry in self._entries.values()\n for acct, amt in entry if acct == account), Decimal('0'))\n\n def trial_balance(self):\n tb = {}\n for entry in self._entries.values():\n for acct, amt in entry:\n tb[acct] = tb.get(acct, Decimal('0')) + amt\n return tb\n\n\nclass TestAccrueInterest(unittest.TestCase):\n def test_worked_example_rounds_up(self):\n self.assertEqual(accrue_interest(Decimal('1000.00'), Decimal('0.05'), 31),\n Decimal('4.25'))\n\n def test_half_even_tie_down(self):\n # 1250 * 0.0365 * 1 / 365 = 0.125 exactly -> rounds to even: 0.12\n self.assertEqual(accrue_interest(Decimal('1250'), Decimal('0.0365'), 1),\n Decimal('0.12'))\n\n def test_half_even_tie_up(self):\n # 1350 * 0.0365 * 1 / 365 = 0.135 exactly -> rounds to even: 0.14\n self.assertEqual(accrue_interest(Decimal('1350'), Decimal('0.0365'), 1),\n Decimal('0.14'))\n\n def test_zero_days(self):\n self.assertEqual(accrue_interest(Decimal('500.00'), Decimal('0.09'), 0),\n Decimal('0.00'))\n\n def test_invalid_inputs(self):\n with self.assertRaises(ValueError):\n accrue_interest(Decimal('-1'), Decimal('0.05'), 10)\n with self.assertRaises(ValueError):\n accrue_interest(Decimal('1'), Decimal('0.05'), -1)\n with self.assertRaises(ValueError):\n accrue_interest(Decimal('1'), Decimal('0.05'), 10, basis=0)\n with self.assertRaises(TypeError):\n accrue_interest(1.5, Decimal('0.05'), 10)\n\n\nclass TestAllocate(unittest.TestCase):\n def test_worked_example_tie_goes_to_first(self):\n self.assertEqual(allocate(Decimal('0.10'),\n [Decimal('1'), Decimal('1'), Decimal('1')]),\n [Decimal('0.04'), Decimal('0.03'), Decimal('0.03')])\n\n def test_parts_sum_exactly_on_hard_case(self):\n parts = allocate(Decimal('100.00'),\n [Decimal('3'), Decimal('7'), Decimal('11'), Decimal('39')])\n self.assertEqual(sum(parts, Decimal('0')), Decimal('100.00'))\n self.assertTrue(all(p == p.quantize(CENT) for p in parts))\n\n def test_negative_amount_allocation(self):\n parts = allocate(Decimal('-10.00'),\n [Decimal('1'), Decimal('1'), Decimal('1')])\n self.assertEqual(sum(parts, Decimal('0')), Decimal('-10.00'))\n self.assertEqual(parts, [Decimal('-3.33'), Decimal('-3.33'), Decimal('-3.34')])\n\n def test_zero_weight_gets_zero(self):\n parts = allocate(Decimal('10.00'), [Decimal('0'), Decimal('1')])\n self.assertEqual(parts, [Decimal('0.00'), Decimal('10.00')])\n\n def test_invalid_weights(self):\n with self.assertRaises(ValueError):\n allocate(Decimal('1.00'), [])\n with self.assertRaises(ValueError):\n allocate(Decimal('1.00'), [Decimal('-1')])\n with self.assertRaises(ValueError):\n allocate(Decimal('1.00'), [Decimal('0'), Decimal('0')])\n with self.assertRaises(TypeError):\n allocate(Decimal('1.00'), [0.5])\n\n\nclass TestLedger(unittest.TestCase):\n def test_post_and_balance(self):\n led = Ledger()\n led.post('E1', {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')})\n self.assertEqual(led.balance('Cash'), Decimal('100.00'))\n self.assertEqual(led.balance('Revenue'), Decimal('-100.00'))\n\n def test_trial_balance_sums_to_zero(self):\n led = Ledger()\n led.post('E1', {'Cash': Decimal('250.00'),\n 'Revenue': Decimal('-250.00')})\n led.post('E2', {'Rent Expense': Decimal('50.00'),\n 'Cash': Decimal('-50.00')})\n tb = led.trial_balance()\n self.assertEqual(sum(tb.values(), Decimal('0')), Decimal('0'))\n self.assertEqual(tb['Cash'], Decimal('200.00'))\n self.assertEqual(tb['Rent Expense'], Decimal('50.00'))\n\n def test_unbalanced_entry_rejected(self):\n led = Ledger()\n with self.assertRaises(UnbalancedEntryError):\n led.post('E1', {'Cash': Decimal('100.00'),\n 'Revenue': Decimal('-99.99')})\n self.assertEqual(led.trial_balance(), {})\n\n def test_duplicate_entry_rejected(self):\n led = Ledger()\n lines = {'Cash': Decimal('10.00'), 'Revenue': Decimal('-10.00')}\n led.post('E1', lines)\n with self.assertRaises(DuplicateEntryError):\n led.post('E1', lines)\n\n def test_float_amount_rejected(self):\n led = Ledger()\n with self.assertRaises(TypeError):\n led.post('E1', {'Cash': 100.00, 'Revenue': Decimal('-100')})\n\n def test_posted_lines_cannot_be_mutated_afterwards(self):\n led = Ledger()\n lines = {'Cash': Decimal('10.00'), 'Revenue': Decimal('-10.00')}\n led.post('E1', lines)\n lines['Cash'] = Decimal('999.00') # caller mutates its own dict\n self.assertEqual(led.balance('Cash'), Decimal('10.00'))\n self.assertEqual(sum(led.trial_balance().values(), Decimal('0')),\n Decimal('0'))\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)"}], "meta": {"idx": 2243, "topic": "unit tests for accounting functions", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2848, "latency_s": 95.6}} +{"prompt": [{"role": "user", "content": "You are given a CSV file of double-entry ledger postings. Each row contains: date (ISO string), account (string like 'ASSET:CASH', 'LIAB:AP', 'EQUITY:CAPITAL', 'REV:SERVICES', 'EXP:RENT'), debit (string amount), credit (string amount). Exactly one side of each row is non-zero. Write a program that reads the CSV from stdin and prints a financial summary. Rules: (1) Parse all amounts as Decimal with 2-decimal quantization using ROUND_HALF_UP; reject any row where both debit and credit are non-zero or both are zero, printing 'INVALID ROW: ' and exiting with status 1. (2) Compute each account's net debit balance (debits minus credits). (3) Derive: total_assets = sum of net balances of accounts starting with 'ASSET:', total_liabilities = negative of the net balance of 'LIAB:' accounts (liabilities are credit-normal), equity = negative of the net balance of 'EQUITY:' accounts, revenue = negative of the net balance of 'REV:' accounts, expenses = net balance of 'EXP:' accounts. (4) Net income = revenue - expenses. (5) Print exactly five lines: 'ASSETS: ', 'LIABILITIES: ', 'EQUITY: ', 'NET_INCOME: ', 'BALANCED: YES' if assets = liabilities + equity + net_income (compare quantized values), otherwise 'BALANCED: NO'. All printed amounts must be formatted with exactly two decimal places. Example: for input rows posting 1000.00 debit to ASSET:CASH, 1000.00 credit to EQUITY:CAPITAL, 250.50 debit to EXP:RENT, 400.00 credit to ASSET:CASH, 700.00 debit to ASSET:CASH, 700.00 credit to REV:SERVICES, the output is ASSETS: 1300.00, LIABILITIES: 0.00, EQUITY: 1000.00, NET_INCOME: 449.50, BALANCED: YES (1300.00 = 0.00 + 1000.00 + 449.50)."}], "completion": [{"role": "assistant", "content": "import sys\nimport csv\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef to_money(value_str):\n return Decimal(value_str or '0').quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef main():\n reader = csv.DictReader(sys.stdin)\n balances = {}\n\n for row in reader:\n account = row['account'].strip()\n debit = to_money(row['debit'])\n credit = to_money(row['credit'])\n\n if (debit == 0) == (credit == 0):\n print('INVALID ROW: {}'.format(account))\n sys.exit(1)\n\n net = debit - credit\n balances[account] = balances.get(account, Decimal('0')) + net\n\n total_assets = Decimal('0')\n total_liabilities = Decimal('0')\n total_equity = Decimal('0')\n total_revenue = Decimal('0')\n total_expenses = Decimal('0')\n\n for account, balance in balances.items():\n if account.startswith('ASSET:'):\n total_assets += balance\n elif account.startswith('LIAB:'):\n total_liabilities -= balance\n elif account.startswith('EQUITY:'):\n total_equity -= balance\n elif account.startswith('REV:'):\n total_revenue -= balance\n elif account.startswith('EXP:'):\n total_expenses += balance\n\n net_income = total_revenue - total_expenses\n\n def fmt(value):\n return str(value.quantize(CENT, rounding=ROUND_HALF_UP))\n\n print('ASSETS: ' + fmt(total_assets))\n print('LIABILITIES: ' + fmt(total_liabilities))\n print('EQUITY: ' + fmt(total_equity))\n print('NET_INCOME: ' + fmt(net_income))\n\n lhs = total_assets.quantize(CENT)\n rhs = (total_liabilities + total_equity + net_income).quantize(CENT)\n print('BALANCED: ' + ('YES' if lhs == rhs else 'NO'))\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2270, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "novita", "in_tokens": 204, "out_tokens": 1068, "latency_s": 8.6}} +{"prompt": [{"role": "user", "content": "Implement a double-entry bookkeeping validator and poster. Each journal entry is a dict with an 'id' and a list of lines, where each line is a tuple (account, 'D' or 'C', amount). An entry is valid only if: every amount is a positive Decimal (no zero or negative amounts), the debit side total equals the credit side total exactly (to the cent), and it contains at least two lines. Write a function post_entries(entries) that returns a dict mapping each account to its net balance (debits minus credits) as a Decimal, processing entries in order, and a list of rejected entry ids in the order they were rejected. Invalid entries must be skipped entirely (none of their lines posted) and their ids recorded. Balances should be exact Decimal sums with no rounding applied. For example, given entries [{'id': 'E1', 'lines': [('Cash', 'D', Decimal('100.00')), ('Revenue', 'C', Decimal('100.00'))]}, {'id': 'E2', 'lines': [('Cash', 'D', Decimal('50.00')), ('Revenue', 'C', Decimal('40.00'))]}], the result should be balances {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')} and rejected ['E2'], since E2 does not balance."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef post_entries(entries):\n \"\"\"Post valid double-entry journal entries to ledger balances.\n\n Returns (balances, rejected_ids) where balances maps account ->\n Decimal net balance (debits - credits) and rejected_ids lists the\n ids of invalid entries in the order they were encountered.\n \"\"\"\n balances = {}\n rejected = []\n\n for entry in entries:\n entry_id = entry.get('id')\n lines = entry.get('lines', [])\n valid = len(lines) >= 2\n debit_total = Decimal('0')\n credit_total = Decimal('0')\n\n for account, side, amount in lines:\n if not isinstance(amount, Decimal):\n valid = False\n break\n if amount <= 0:\n valid = False\n break\n if side == 'D':\n debit_total += amount\n elif side == 'C':\n credit_total += amount\n else:\n valid = False\n break\n\n if valid and debit_total != credit_total:\n valid = False\n\n if not valid:\n rejected.append(entry_id)\n continue\n\n for account, side, amount in lines:\n if side == 'D':\n balances[account] = balances.get(account, Decimal('0')) + amount\n else:\n balances[account] = balances.get(account, Decimal('0')) - amount\n\n return balances, rejected\n\n\nif __name__ == '__main__':\n entries = [\n {'id': 'E1', 'lines': [\n ('Cash', 'D', Decimal('100.00')),\n ('Revenue', 'C', Decimal('100.00')),\n ]},\n {'id': 'E2', 'lines': [\n ('Cash', 'D', Decimal('50.00')),\n ('Revenue', 'C', Decimal('40.00')),\n ]},\n {'id': 'E3', 'lines': [\n ('Rent Expense', 'D', Decimal('75.25')),\n ('Supplies', 'D', Decimal('24.75')),\n ('Cash', 'C', Decimal('100.00')),\n ]},\n ]\n balances, rejected = post_entries(entries)\n print(balances)\n print(rejected)"}], "meta": {"idx": 2278, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 823, "latency_s": 7.3}} +{"prompt": [{"role": "user", "content": "You are given a CSV file of bank transactions with the header `date,description,amount`. Write a program that reads a file named `transactions.csv`, validates each row, and produces a report. A row is valid if: the date matches the format YYYY-MM-DD, the description is non-empty, and the amount is a decimal number (positive or negative) with at most two decimal places. Invalid rows should be skipped and counted. For the valid transactions, compute the net balance using the `decimal.Decimal` type (no floats), rounded to 2 decimal places with ROUND_HALF_UP. Finally, write all valid transactions (unchanged, in original order) to `valid_transactions.csv` with the same header, and print exactly two lines: `Valid: ` and `Balance: ` where balance is formatted with exactly two decimal places. For example, given input `date,description,amount` / `2024-01-15,Coffee shop,-4.50` / `2024-01-16,Invalid row` / `2024-01-17,Paycheck,2500.755` / `2024-01-18,Refund,10.00`, the program prints `Valid: 2` and `Balance: 5.50`, and `valid_transactions.csv` contains the Coffee shop and Refund rows."}], "completion": [{"role": "assistant", "content": "import csv\nimport re\nfrom decimal import Decimal, ROUND_HALF_UP, InvalidOperation\nfrom datetime import datetime\n\nINPUT_FILE = \"transactions.csv\"\nOUTPUT_FILE = \"valid_transactions.csv\"\n\nAMOUNT_RE = re.compile(r\"^-?\\d+(\\.\\d{1,2})?$\")\nDATE_RE = re.compile(r\"^\\d{4}-\\d{2}-\\d{2}$\")\n\n\ndef is_valid_date(date_str):\n if not DATE_RE.match(date_str):\n return False\n try:\n datetime.strptime(date_str, \"%Y-%m-%d\")\n return True\n except ValueError:\n return False\n\n\ndef is_valid_row(date, description, amount):\n if not is_valid_date(date.strip()):\n return False\n if not description.strip():\n return False\n if not AMOUNT_RE.match(amount.strip()):\n return False\n return True\n\n\ndef main():\n valid_rows = []\n balance = Decimal(\"0\")\n\n with open(INPUT_FILE, newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n header = next(reader, None)\n if header is None:\n print(\"Valid: 0\")\n print(\"Balance: 0.00\")\n with open(OUTPUT_FILE, \"w\", newline=\"\", encoding=\"utf-8\") as out:\n writer = csv.writer(out)\n writer.writerow([\"date\", \"description\", \"amount\"])\n return\n\n for row in reader:\n if len(row) != 3:\n continue\n date, description, amount = row\n if not is_valid_row(date, description, amount):\n continue\n valid_rows.append(row)\n try:\n value = Decimal(amount.strip())\n except InvalidOperation:\n continue\n balance += value\n\n with open(OUTPUT_FILE, \"w\", newline=\"\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n writer.writerow([\"date\", \"description\", \"amount\"])\n writer.writerows(valid_rows)\n\n rounded_balance = balance.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP)\n print(f\"Valid: {len(valid_rows)}\")\n print(f\"Balance: {rounded_balance:.2f}\")\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2277, "topic": "transaction CSV import, validation, and export", "difficulty": "easy", "provider": "novita", "in_tokens": 200, "out_tokens": 879, "latency_s": 6.6}} +{"prompt": [{"role": "user", "content": "Implement a general-ledger engine (standard library only, monetary values handled with decimal.Decimal) where every account has a kind (ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE) plus an optional contra flag that flips its normal balance side (so a contra-asset normally carries a credit balance). A journal entry is a list of lines (account_name, debit, credit) and must pass all posting rules: it has at least two lines, every account exists, no account appears on more than one line, no line carries both a debit and a credit, amounts are non-negative and are rounded to the nearest cent with ROUND_HALF_UP before any check, and total debits must equal total credits exactly; a valid entry updates per-account debit/credit totals while an invalid one is rejected with an error message and changes nothing. Each account's balance must be reported on its normal side (positive means normal side, negative means the balance 'flipped' side), and a trial_balance() method returns the ledger's total debits and total credits. Worked example: with accounts Cash(ASSET), AR(ASSET), Equipment(ASSET), AccumDep(ASSET, contra), AP(LIABILITY), Revenue(REVENUE), DepExp(EXPENSE), posting the entries [Dr Equipment 1000.00 / Cr AP 1000.00], [Dr DepExp 50.00 / Cr AccumDep 50.00], [Dr AR 200.504 / Cr Revenue 200.504] (both sides round to 200.50), [Dr Cash 100.00 / Cr AR 100.00], and [Dr Cash 10.00 / Cr Revenue 9.99] (rejected as unbalanced) must yield balances Cash 100.00, AR 100.50, Equipment 1000.00, AccumDep 50.00, AP 1000.00, Revenue 200.50, DepExp 50.00, and a trial balance of 1350.50 debits and 1350.50 credits."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\nDEBIT_NORMAL = {\"ASSET\", \"EXPENSE\"}\nCREDIT_NORMAL = {\"LIABILITY\", \"EQUITY\", \"REVENUE\"}\nALL_KINDS = DEBIT_NORMAL | CREDIT_NORMAL\n\n\ndef to_cents(value):\n \"\"\"Round a money amount (str/int/Decimal) to the nearest cent, HALF_UP.\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\nclass Account:\n def __init__(self, name, kind, contra=False):\n if kind not in ALL_KINDS:\n raise ValueError(\"unknown account kind: %s\" % kind)\n self.name = name\n self.kind = kind\n self.contra = contra\n self.debits = ZERO\n self.credits = ZERO\n\n @property\n def normal_side(self):\n side = \"debit\" if self.kind in DEBIT_NORMAL else \"credit\"\n if self.contra:\n side = \"credit\" if side == \"debit\" else \"debit\"\n return side\n\n def balance(self):\n \"\"\"Balance expressed on the account's normal side.\"\"\"\n if self.normal_side == \"debit\":\n return (self.debits - self.credits).quantize(CENT)\n return (self.credits - self.debits).quantize(CENT)\n\n\nclass Ledger:\n def __init__(self):\n self.accounts = {}\n\n def add_account(self, name, kind, contra=False):\n self.accounts[name] = Account(name, kind, contra)\n return self.accounts[name]\n\n def post(self, entry):\n \"\"\"Validate and post a journal entry.\n\n Returns a list of error strings; an empty list means the entry was\n posted. An invalid entry changes nothing in the ledger.\n \"\"\"\n errors = []\n if len(entry) < 2:\n return [\"entry must contain at least two lines\"]\n\n parsed = []\n seen = set()\n total_debits = ZERO\n total_credits = ZERO\n\n for line in entry:\n if len(line) != 3:\n errors.append(\"malformed line: %r\" % (line,))\n continue\n acct_name, debit, credit = line\n if acct_name not in self.accounts:\n errors.append(\"unknown account: %s\" % acct_name)\n continue\n if acct_name in seen:\n errors.append(\n \"account appears on more than one line: %s\" % acct_name)\n continue\n seen.add(acct_name)\n try:\n d = ZERO if debit in (None, \"\") else to_cents(debit)\n c = ZERO if credit in (None, \"\") else to_cents(credit)\n except Exception:\n errors.append(\"invalid amount on line for %s\" % acct_name)\n continue\n if d < ZERO or c < ZERO:\n errors.append(\"negative amount on line for %s\" % acct_name)\n continue\n if d > ZERO and c > ZERO:\n errors.append(\n \"line for %s carries both a debit and a credit\" % acct_name)\n continue\n parsed.append((self.accounts[acct_name], d, c))\n total_debits += d\n total_credits += c\n\n if not errors and total_debits != total_credits:\n errors.append(\"unbalanced entry: debits %s != credits %s\"\n % (total_debits, total_credits))\n\n if errors:\n return errors\n\n for account, d, c in parsed:\n account.debits += d\n account.credits += c\n return []\n\n def balances(self):\n return {name: acct.balance() for name, acct in self.accounts.items()}\n\n def trial_balance(self):\n td = sum((a.debits for a in self.accounts.values()), ZERO).quantize(CENT)\n tc = sum((a.credits for a in self.accounts.values()), ZERO).quantize(CENT)\n return td, tc\n\n\nif __name__ == \"__main__\":\n ledger = Ledger()\n ledger.add_account(\"Cash\", \"ASSET\")\n ledger.add_account(\"AR\", \"ASSET\")\n ledger.add_account(\"Equipment\", \"ASSET\")\n ledger.add_account(\"AccumDep\", \"ASSET\", contra=True)\n ledger.add_account(\"AP\", \"LIABILITY\")\n ledger.add_account(\"Revenue\", \"REVENUE\")\n ledger.add_account(\"DepExp\", \"EXPENSE\")\n\n entries = [\n [(\"Equipment\", \"1000.00\", None), (\"AP\", None, \"1000.00\")],\n [(\"DepExp\", \"50.00\", None), (\"AccumDep\", None, \"50.00\")],\n [(\"AR\", \"200.504\", None), (\"Revenue\", None, \"200.504\")],\n [(\"Cash\", \"100.00\", None), (\"AR\", None, \"100.00\")],\n [(\"Cash\", \"10.00\", None), (\"Revenue\", None, \"9.99\")],\n ]\n\n for i, entry in enumerate(entries, 1):\n errs = ledger.post(entry)\n if errs:\n print(\"entry %d: rejected -> %s\" % (i, \"; \".join(errs)))\n else:\n print(\"entry %d: posted\" % i)\n\n for name, bal in ledger.balances().items():\n print(\"%-10s %10s\" % (name, bal))\n\n td, tc = ledger.trial_balance()\n print(\"trial balance: debits=%s credits=%s\" % (td, tc))"}], "meta": {"idx": 2276, "topic": "double-entry journal entries and posting rules", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1692, "latency_s": 47.5}} +{"prompt": [{"role": "user", "content": "A bookkeeping service needs utilities for a company whose fiscal year begins in an arbitrary month fy_start_month (e.g., 4 for April), so fiscal Q1 covers months fy_start_month, fy_start_month+1, fy_start_month+2 (mod 12), and the fiscal year is labeled by the calendar year in which it begins. Implement four functions using only the standard library, with all money handled as Decimal: (1) month_end(y, m) returning the datetime.date of the last day of month m in year y; (2) fiscal_year_and_quarter(d, fy_start_month) returning the tuple (fiscal_year, quarter) with quarter in 1..4 for a datetime.date d; (3) quarterly_totals(entries, fy_start_month, fiscal_year) taking entries as (iso_date_string, account, amount) tuples, raising ValueError if the ledger does not sum to exactly zero, ignoring entries outside the requested fiscal year, and returning {quarter: {account: total}} for all four quarters with every account total quantized to cents using ROUND_HALF_UP; (4) allocate(amount, weights) splitting a non-negative cent-precision amount across positive weights penny-perfectly: each exact share is first rounded DOWN to cents, then the leftover cents are handed out one at a time to the shares with the largest fractional remainder (exact minus floored value), ties broken by lowest index, so the shares always sum to the original amount. Worked example: with fy_start_month=4 and fiscal_year=2024, the entries [(\"2024-04-30\",\"Cash\",\"1000.00\"),(\"2024-05-15\",\"Revenue\",\"-1000.00\"),(\"2024-08-31\",\"Cash\",\"250.50\"),(\"2024-09-01\",\"Revenue\",\"-250.50\"),(\"2025-01-10\",\"Rent Expense\",\"300.00\"),(\"2025-01-10\",\"Cash\",\"-300.00\")] must produce Q1 {\"Cash\": 1000.00, \"Revenue\": -1000.00}, Q2 {\"Cash\": 250.50, \"Revenue\": -250.50}, Q3 {}, and Q4 {\"Rent Expense\": 300.00, \"Cash\": -300.00}; additionally allocate(Decimal(\"100.00\"), [1, 1, 1]) must return [Decimal(\"33.34\"), Decimal(\"33.33\"), Decimal(\"33.33\")]."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP, ROUND_FLOOR\n\nCENT = Decimal(\"0.01\")\n\n\ndef month_end(y, m):\n \"\"\"Return the date of the last day of month m in year y.\"\"\"\n if not 1 <= m <= 12:\n raise ValueError(\"month must be in 1..12\")\n return date(y, m, calendar.monthrange(y, m)[1])\n\n\ndef fiscal_quarter_months(fy_start_month):\n \"\"\"Return the calendar month numbers for fiscal quarters 1..4.\"\"\"\n if not 1 <= fy_start_month <= 12:\n raise ValueError(\"fiscal start month must be in 1..12\")\n return [\n [((fy_start_month - 1 + q * 3 + i) % 12) + 1 for i in range(3)]\n for q in range(4)\n ]\n\n\ndef fiscal_year_and_quarter(d, fy_start_month):\n \"\"\"Return (fiscal_year, quarter) for date d.\n\n The fiscal year is labeled by the calendar year in which it begins.\n \"\"\"\n if not 1 <= fy_start_month <= 12:\n raise ValueError(\"fiscal start month must be in 1..12\")\n fiscal_year = d.year if d.month >= fy_start_month else d.year - 1\n quarter = ((d.month - fy_start_month) % 12) // 3 + 1\n return fiscal_year, quarter\n\n\ndef quarterly_totals(entries, fy_start_month, fiscal_year):\n \"\"\"Aggregate (iso_date, account, amount) entries per fiscal quarter.\n\n Raises ValueError if the whole ledger does not sum to exactly zero.\n Entries outside the requested fiscal year are ignored.\n \"\"\"\n ledger_sum = Decimal(\"0\")\n totals = {q: {} for q in (1, 2, 3, 4)}\n for iso_date, account, amount in entries:\n amt = Decimal(str(amount))\n ledger_sum += amt\n d = date.fromisoformat(iso_date)\n fy, quarter = fiscal_year_and_quarter(d, fy_start_month)\n if fy != fiscal_year:\n continue\n bucket = totals[quarter]\n bucket[account] = bucket.get(account, Decimal(\"0\")) + amt\n if ledger_sum != 0:\n raise ValueError(\"ledger is not balanced: sum of amounts is %s\" % ledger_sum)\n for quarter in totals:\n for account in totals[quarter]:\n totals[quarter][account] = totals[quarter][account].quantize(\n CENT, rounding=ROUND_HALF_UP\n )\n return totals\n\n\ndef allocate(amount, weights):\n \"\"\"Penny-perfect proportional split of a non-negative amount.\n\n Exact shares are floored to cents, then leftover cents go one at a\n time to the shares with the largest fractional remainder (ties\n broken by lowest index), so the result always sums to `amount`.\n \"\"\"\n amount = Decimal(str(amount)).quantize(CENT, rounding=ROUND_HALF_UP)\n if amount < 0:\n raise ValueError(\"amount must be non-negative\")\n weights = [Decimal(str(w)) for w in weights]\n if not weights:\n raise ValueError(\"weights must be non-empty\")\n if any(w <= 0 for w in weights):\n raise ValueError(\"weights must be positive\")\n total_weight = sum(weights)\n exact = [amount * w / total_weight for w in weights]\n shares = [e.quantize(CENT, rounding=ROUND_FLOOR) for e in exact]\n residual_cents = int(((amount - sum(shares)) / CENT).to_integral_value())\n order = sorted(range(len(shares)), key=lambda i: (-(exact[i] - shares[i]), i))\n for k in range(residual_cents):\n shares[order[k % len(order)]] += CENT\n return shares\n\n\nif __name__ == \"__main__\":\n # Month-end and fiscal-calendar checks\n assert month_end(2024, 2) == date(2024, 2, 29)\n assert month_end(2023, 2) == date(2023, 2, 28)\n assert fiscal_year_and_quarter(date(2024, 4, 1), 4) == (2024, 1)\n assert fiscal_year_and_quarter(date(2024, 6, 30), 4) == (2024, 1)\n assert fiscal_year_and_quarter(date(2024, 7, 1), 4) == (2024, 2)\n assert fiscal_year_and_quarter(date(2025, 1, 10), 4) == (2024, 4)\n assert fiscal_year_and_quarter(date(2025, 3, 31), 4) == (2024, 4)\n assert fiscal_year_and_quarter(date(2024, 12, 31), 1) == (2024, 4)\n assert fiscal_quarter_months(4) == [[4, 5, 6], [7, 8, 9], [10, 11, 12], [1, 2, 3]]\n\n # Worked example from the statement\n entries = [\n (\"2024-04-30\", \"Cash\", \"1000.00\"),\n (\"2024-05-15\", \"Revenue\", \"-1000.00\"),\n (\"2024-08-31\", \"Cash\", \"250.50\"),\n (\"2024-09-01\", \"Revenue\", \"-250.50\"),\n (\"2025-01-10\", \"Rent Expense\", \"300.00\"),\n (\"2025-01-10\", \"Cash\", \"-300.00\"),\n ]\n expected = {\n 1: {\"Cash\": Decimal(\"1000.00\"), \"Revenue\": Decimal(\"-1000.00\")},\n 2: {\"Cash\": Decimal(\"250.50\"), \"Revenue\": Decimal(\"-250.50\")},\n 3: {},\n 4: {\"Rent Expense\": Decimal(\"300.00\"), \"Cash\": Decimal(\"-300.00\")},\n }\n result = quarterly_totals(entries, 4, 2024)\n assert result == expected, result\n\n # An unbalanced ledger must be rejected\n try:\n quarterly_totals(\n [(\"2024-05-01\", \"Cash\", \"10.00\"), (\"2024-05-02\", \"Revenue\", \"-9.99\")],\n 4, 2024,\n )\n raise AssertionError(\"expected ValueError for unbalanced ledger\")\n except ValueError:\n pass\n\n # Allocation checks\n assert allocate(Decimal(\"100.00\"), [1, 1, 1]) == [\n Decimal(\"33.34\"), Decimal(\"33.33\"), Decimal(\"33.33\"),\n ]\n assert allocate(Decimal(\"0.02\"), [1, 1, 1]) == [\n Decimal(\"0.01\"), Decimal(\"0.01\"), Decimal(\"0.00\"),\n ]\n split = allocate(Decimal(\"1000.00\"), [1, 2, 3, 7])\n assert sum(split) == Decimal(\"1000.00\")\n assert split == [\n Decimal(\"76.92\"), Decimal(\"153.85\"), Decimal(\"230.77\"), Decimal(\"538.46\"),\n ]\n assert allocate(Decimal(\"50.00\"), [1]) == [Decimal(\"50.00\")]\n\n print(\"All checks passed.\")"}], "meta": {"idx": 2274, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1948, "latency_s": 59.5}} +{"prompt": [{"role": "user", "content": "Write a function `amortization_schedule(principal, annual_rate, years, payments_per_year=12)` that builds an amortization schedule for a fixed-rate loan. All money must be handled with `decimal.Decimal` rounded to cents with `ROUND_HALF_UP` at each payment. The monthly payment is the standard annuity payment: A = P * r / (1 - (1+r)**(-n)), where r = annual_rate/payments_per_year and n = years*payments_per_year; round A to cents. Each payment applies interest = round(balance * r) first, then principal = payment - interest, and the balance is reduced accordingly; the final payment must be adjusted so the balance reaches exactly 0.00. Return a list of tuples (payment_number, payment, interest, principal, balance). For example, a $100,000 loan at 6.5% annual for 30 years monthly gives payment 632.07, first row (1, 632.07, 541.67, 90.40, 99909.60), and the final row must show balance 0.00. Raise ValueError if principal <= 0, annual_rate < 0, years <= 0, or payments_per_year <= 0."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _round(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef amortization_schedule(principal, annual_rate, years, payments_per_year=12):\n principal = Decimal(str(principal))\n annual_rate = Decimal(str(annual_rate))\n years = Decimal(str(years))\n payments_per_year = int(payments_per_year)\n\n if principal <= 0 or annual_rate < 0 or years <= 0 or payments_per_year <= 0:\n raise ValueError(\"Invalid loan parameters\")\n\n n = int(years * payments_per_year)\n r = annual_rate / Decimal(payments_per_year)\n\n if r == 0:\n payment = _round(principal / Decimal(n))\n else:\n factor = (Decimal(1) + r) ** Decimal(-n)\n payment = _round(principal * r / (Decimal(1) - factor))\n\n schedule = []\n balance = principal\n for k in range(1, n + 1):\n interest = _round(balance * r)\n if k == n:\n principal_part = balance\n pay = _round(balance + interest)\n else:\n principal_part = payment - interest\n pay = payment\n balance = balance - principal_part\n if balance < 0:\n balance = Decimal('0.00')\n schedule.append((k, pay, interest, principal_part, _round(balance)))\n if balance == 0 and k < n:\n break\n return schedule\n\nif __name__ == \"__main__\":\n rows = amortization_schedule(100000, 0.065, 30)\n print(rows[0])\n print(rows[-1])"}], "meta": {"idx": 2283, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 633, "latency_s": 3.7}} +{"prompt": [{"role": "user", "content": "A trial balance lists every ledger account with its debit (Dr) or credit (Cr) balance, and the books balance only when total debits equal total credits. Write a function `check_trial_balance(entries)` that takes a list of tuples `(account_name, side, amount)` where side is the string 'Dr' or 'Cr' and amount is a Decimal or a string representing a monetary amount. The function should return a tuple `(total_dr, total_cr, balanced)` where total_dr and total_cr are Decimals rounded to 2 decimal places and balanced is True if they are equal, otherwise False. Use Decimal arithmetic for exact money handling (ROUND_HALF_UP). For example, given [('Cash','Dr','1500.00'), ('Revenue','Cr','900.505'), ('Bank Loan','Cr','599.495')], the amounts round so that total_dr is 1500.00, total_cr is 900.51 + 599.50 = 1500.01, so the result is (Decimal('1500.00'), Decimal('1500.01'), False)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef check_trial_balance(entries):\n \"\"\"Return (total_dr, total_cr, balanced) for a list of\n (account_name, side, amount) trial-balance entries.\"\"\"\n two_places = Decimal('0.01')\n total_dr = Decimal('0')\n total_cr = Decimal('0')\n\n for account_name, side, amount in entries:\n value = Decimal(str(amount))\n if side == 'Dr':\n total_dr += value\n elif side == 'Cr':\n total_cr += value\n else:\n raise ValueError(f\"Invalid side {side!r} for account {account_name!r}; expected 'Dr' or 'Cr'\")\n\n total_dr = total_dr.quantize(two_places, rounding=ROUND_HALF_UP)\n total_cr = total_cr.quantize(two_places, rounding=ROUND_HALF_UP)\n\n return (total_dr, total_cr, total_dr == total_cr)\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', 'Dr', '1500.00'),\n ('Revenue', 'Cr', '900.505'),\n ('Bank Loan', 'Cr', '599.495'),\n ]\n print(check_trial_balance(entries))\n # (Decimal('1500.00'), Decimal('1500.01'), False)\n\n balanced_entries = [\n ('Cash', 'Dr', '100.00'),\n ('Equipment', 'Dr', '250.00'),\n ('Revenue', 'Cr', '350.00'),\n ]\n print(check_trial_balance(balanced_entries))\n # (Decimal('350.00'), Decimal('350.00'), True)"}], "meta": {"idx": 2272, "topic": "trial balance construction and imbalance detection", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 566, "latency_s": 78.5}} +{"prompt": [{"role": "user", "content": "You are building a small bookkeeping routine that adds VAT to a list of net invoice line amounts. Write a function `apply_vat(lines, vat_rate)` that takes a list of strings representing net amounts in euros (e.g., '19.99') and a VAT rate given as a string percentage (e.g., '19.00' for 19%). For each line, compute the VAT amount and the gross amount using Decimal arithmetic with ROUND_HALF_UP rounding to 2 decimal places. Return a list of dictionaries, each with keys 'net', 'vat', 'gross' (all as strings with exactly 2 decimals), and also return the invoice totals: a dictionary with keys 'net_total', 'vat_total', 'gross_total' computed as the sum of the rounded line values (so the ledger balances exactly). For example, apply_vat(['19.99', '0.05'], '19.00') returns lines [{'net': '19.99', 'vat': '3.80', 'gross': '23.79'}, {'net': '0.05', 'vat': '0.01', 'gross': '0.06'}] and totals {'net_total': '20.04', 'vat_total': '3.81', 'gross_total': '23.85'}. Use only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _q2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef apply_vat(lines, vat_rate):\n rate = Decimal(vat_rate) / Decimal('100')\n result_lines = []\n net_total = Decimal('0')\n vat_total = Decimal('0')\n gross_total = Decimal('0')\n\n for line in lines:\n net = _q2(Decimal(line))\n vat = _q2(net * rate)\n gross = _q2(net + vat)\n\n result_lines.append({\n 'net': str(net),\n 'vat': str(vat),\n 'gross': str(gross),\n })\n\n net_total += net\n vat_total += vat\n gross_total += gross\n\n totals = {\n 'net_total': str(_q2(net_total)),\n 'vat_total': str(_q2(vat_total)),\n 'gross_total': str(_q2(gross_total)),\n }\n\n return result_lines, totals\n\n\nif __name__ == '__main__':\n lines, totals = apply_vat(['19.99', '0.05'], '19.00')\n print(lines)\n print(totals)\n assert lines == [\n {'net': '19.99', 'vat': '3.80', 'gross': '23.79'},\n {'net': '0.05', 'vat': '0.01', 'gross': '0.06'},\n ]\n assert totals == {'net_total': '20.04', 'vat_total': '3.81', 'gross_total': '23.85'}\n print('All checks passed.')"}], "meta": {"idx": 2282, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 574, "latency_s": 4.9}} +{"prompt": [{"role": "user", "content": "Write a function `calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions)` that computes an employee's net pay from a payroll run. All monetary values must be handled with the `Decimal` type and rounded to 2 decimal places using ROUND_HALF_UP. The taxable pay equals gross pay minus pre-tax deductions (such as health insurance premiums), floored at zero. Federal and state withholdings are each computed as the taxable pay multiplied by the given rates (given as Decimal percentages, e.g. Decimal('12') means 12%). Net pay equals taxable pay minus both withholdings. The function should return a dict with keys 'taxable_pay', 'federal_withholding', 'state_withholding', and 'net_pay', all as Decimal values rounded to cents. For example, with gross_pay=Decimal('2500.00'), federal_rate=Decimal('12'), state_rate=Decimal('5'), and pre_tax_deductions=Decimal('200.00'), taxable pay is 2300.00, federal withholding is 276.00, state withholding is 115.00, and net pay is 1909.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions):\n \"\"\"Compute payroll withholdings and net pay using Decimal arithmetic.\n\n Args:\n gross_pay: Decimal gross wages for the pay period.\n federal_rate: Decimal federal withholding percentage (e.g. 12 means 12%).\n state_rate: Decimal state withholding percentage.\n pre_tax_deductions: Decimal pre-tax deductions (insurance, etc.).\n\n Returns:\n Dict of Decimal amounts rounded to cents (ROUND_HALF_UP).\n \"\"\"\n if not isinstance(gross_pay, Decimal):\n gross_pay = Decimal(str(gross_pay))\n if not isinstance(pre_tax_deductions, Decimal):\n pre_tax_deductions = Decimal(str(pre_tax_deductions))\n if not isinstance(federal_rate, Decimal):\n federal_rate = Decimal(str(federal_rate))\n if not isinstance(state_rate, Decimal):\n state_rate = Decimal(str(state_rate))\n\n cent = Decimal('0.01')\n\n taxable_pay = gross_pay - pre_tax_deductions\n if taxable_pay < Decimal('0'):\n taxable_pay = Decimal('0')\n taxable_pay = taxable_pay.quantize(cent, rounding=ROUND_HALF_UP)\n\n federal_withholding = (taxable_pay * federal_rate / Decimal('100')).quantize(\n cent, rounding=ROUND_HALF_UP\n )\n state_withholding = (taxable_pay * state_rate / Decimal('100')).quantize(\n cent, rounding=ROUND_HALF_UP\n )\n\n net_pay = (taxable_pay - federal_withholding - state_withholding).quantize(\n cent, rounding=ROUND_HALF_UP\n )\n\n return {\n 'taxable_pay': taxable_pay,\n 'federal_withholding': federal_withholding,\n 'state_withholding': state_withholding,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = calculate_net_pay(\n Decimal('2500.00'), Decimal('12'), Decimal('5'), Decimal('200.00')\n )\n print(result)\n # {'taxable_pay': Decimal('2300.00'), 'federal_withholding': Decimal('276.00'),\n # 'state_withholding': Decimal('115.00'), 'net_pay': Decimal('1909.00')}\n assert result['taxable_pay'] == Decimal('2300.00')\n assert result['federal_withholding'] == Decimal('276.00')\n assert result['state_withholding'] == Decimal('115.00')\n assert result['net_pay'] == Decimal('1909.00')\n\n # Deductions exceed gross pay: taxable pay floors at zero.\n result2 = calculate_net_pay(\n Decimal('100.00'), Decimal('10'), Decimal('3'), Decimal('150.00')\n )\n assert result2['taxable_pay'] == Decimal('0.00')\n assert result2['net_pay'] == Decimal('0.00')\n\n # Rounding check: 12.345 rounds half-up.\n result3 = calculate_net_pay(\n Decimal('100.00'), Decimal('12.35'), Decimal('0'), Decimal('5.00')\n )\n assert result3['federal_withholding'] == Decimal('11.72')\n print('All checks passed.')"}], "meta": {"idx": 2285, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 980, "latency_s": 8.1}} +{"prompt": [{"role": "user", "content": "Write a function `amortization_schedule(principal, annual_rate, years, payment=None)` that builds a monthly loan amortization ledger using the `decimal.Decimal` type with two-decimal (cent) rounding via `ROUND_HALF_UP` at every step. The loan has `years*12` monthly payments; the monthly interest is `annual_rate/12` applied to the outstanding balance. If `payment` is None, compute the standard annuity payment `P*r/(1-(1+r)**-n)` where `r` is the monthly rate and `n` the number of payments`, rounded UP to the next cent (Decimal quantize with ROUND_CEILING) so the final balance never goes negative; otherwise use the given payment. Each month record interest = round(balance * r), principal = payment - interest, and new balance = old balance - principal, except the final payment must be reduced to exactly clear the balance (payment = balance + interest, principal = balance). Return a list of dictionaries with keys 'month', 'payment', 'interest', 'principal', 'balance', all Decimal values with 2 decimal places. Example: principal=1000.00, annual_rate=0.12, years=1: the computed payment is 88.85, month 1 has interest 10.00, principal 78.85, balance 921.15, and month 12 ends with balance 0.00 (final payment 10.10)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, ROUND_CEILING\n\nTWO = Decimal('0.01')\n\ndef _round2(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef amortization_schedule(principal, annual_rate, years, payment=None):\n principal = Decimal(str(principal))\n annual_rate = Decimal(str(annual_rate))\n n = int(years) * 12\n r = annual_rate / Decimal(12)\n balance = _round2(principal)\n\n if payment is None:\n if r == 0:\n payment = _round2(balance / Decimal(n))\n else:\n factor = (Decimal(1) + r) ** n\n payment = (balance * r / (Decimal(1) - Decimal(1) / factor)).quantize(TWO, rounding=ROUND_CEILING)\n else:\n payment = _round2(Decimal(str(payment)))\n\n schedule = []\n for month in range(1, n + 1):\n interest = _round2(balance * r)\n if month == n or balance + interest <= payment:\n pay = _round2(balance + interest)\n else:\n pay = payment\n principal_part = _round2(pay - interest)\n balance = _round2(balance - principal_part)\n schedule.append({\n 'month': month,\n 'payment': pay,\n 'interest': interest,\n 'principal': principal_part,\n 'balance': balance,\n })\n if balance == 0 and month < n:\n break\n return schedule\n\nif __name__ == '__main__':\n for row in amortization_schedule('1000.00', '0.12', 1):\n print(row)"}], "meta": {"idx": 2287, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 687, "latency_s": 4.8}} +{"prompt": [{"role": "user", "content": "Implement a double-entry bookkeeping engine using dataclasses and Decimal with strict validation. Define an `Account` (chart-of-accounts record) with a 4-digit numeric `code`, a `name`, and a `normal_side` of 'debit' or 'credit'. Define a `JournalLine` holding an account code and a `debit` or `credit` amount given as str/int/Decimal, quantized to cents with ROUND_HALF_EVEN (banker's rounding, so \"12.345\" becomes 12.34 and \"12.355\" becomes 12.36); exactly one side must be a positive amount, otherwise raise `ValidationError`. Define a `JournalEntry` with `entry_id`, a `date`, a `description`, and at least two lines; the sum of debits must exactly equal the sum of credits (after per-line rounding) or raise `UnbalancedEntryError`. A `Ledger` holds the chart of accounts, rejects duplicate entry ids and out-of-chronological-order dates, validates that every line's account code exists, and maintains a running balance per account (debit-normal accounts: debits minus credits; credit-normal: credits minus debits). `Ledger.trial_balance()` returns a dict mapping each account code to its 2-place Decimal balance and must confirm that the total of debit-normal balances equals the total of credit-normal balances, raising `LedgerError` otherwise. Worked example: with accounts 1000 Cash (debit-normal), 2000 Accounts Payable (credit-normal), 4000 Sales Revenue (credit-normal), posting entry E1 dated 2024-01-10 with a debit to 1000 of \"500.00\" and a credit to 4000 of \"500.00\" yields `balance_of(\"1000\") == Decimal(\"500.00\")`, `balance_of(\"4000\") == Decimal(\"500.00\")`, and `trial_balance() == {\"1000\": Decimal(\"500.00\"), \"2000\": Decimal(\"0.00\"), \"4000\": Decimal(\"500.00\")}`; an entry debiting 1000 by 100.00 and crediting 4000 by 99.99 must raise `UnbalancedEntryError`."}], "completion": [{"role": "assistant", "content": "from __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass, field\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_EVEN\nfrom typing import Dict, List, Optional\n\nCENT = Decimal(\"0.01\")\nACCOUNT_CODE_RE = re.compile(r\"\\d{4}\")\n\n\nclass LedgerError(Exception):\n \"\"\"Base error for ledger operations.\"\"\"\n\n\nclass ValidationError(LedgerError):\n \"\"\"Raised when a record violates the accounting schema.\"\"\"\n\n\nclass UnbalancedEntryError(LedgerError):\n \"\"\"Raised when a journal entry's debits do not equal its credits.\"\"\"\n\n\ndef to_money(value) -> Decimal:\n \"\"\"Convert str/int/Decimal to a 2-place Decimal using banker's rounding.\"\"\"\n if isinstance(value, Decimal):\n raw = value\n elif isinstance(value, str):\n try:\n raw = Decimal(value)\n except Exception as exc:\n raise ValidationError(f\"invalid amount literal: {value!r}\") from exc\n elif isinstance(value, int):\n raw = Decimal(value)\n else:\n raise ValidationError(\n f\"amount must be str, int, or Decimal, got {type(value).__name__}\"\n )\n quantized = raw.quantize(CENT, rounding=ROUND_HALF_EVEN)\n if quantized < 0:\n raise ValidationError(f\"amount must be non-negative, got {quantized}\")\n return quantized\n\n\n@dataclass(frozen=True)\nclass Account:\n code: str\n name: str\n normal_side: str # 'debit' or 'credit'\n\n def __post_init__(self):\n if not isinstance(self.code, str) or not ACCOUNT_CODE_RE.fullmatch(self.code):\n raise ValidationError(f\"account code must be 4 digits, got {self.code!r}\")\n if not isinstance(self.name, str) or not self.name.strip():\n raise ValidationError(\"account name must be a non-empty string\")\n if self.normal_side not in (\"debit\", \"credit\"):\n raise ValidationError(\n f\"normal_side must be 'debit' or 'credit', got {self.normal_side!r}\"\n )\n\n\n@dataclass\nclass JournalLine:\n account: str\n debit: Optional[object] = None\n credit: Optional[object] = None\n amount: Decimal = field(init=False, default=Decimal(\"0.00\"))\n side: str = field(init=False, default=\"\")\n\n def __post_init__(self):\n if not isinstance(self.account, str) or not ACCOUNT_CODE_RE.fullmatch(self.account):\n raise ValidationError(f\"line account must be a 4-digit code, got {self.account!r}\")\n has_debit = self.debit is not None\n has_credit = self.credit is not None\n if has_debit == has_credit:\n raise ValidationError(\n \"exactly one of debit/credit must be provided\"\n )\n if has_debit:\n self.amount = to_money(self.debit)\n self.side = \"debit\"\n else:\n self.amount = to_money(self.credit)\n self.side = \"credit\"\n if self.amount == 0:\n raise ValidationError(\"line amount must be positive\")\n\n def signed_amount(self) -> Decimal:\n \"\"\"Positive for debits, negative for credits.\"\"\"\n return self.amount if self.side == \"debit\" else -self.amount\n\n\n@dataclass\nclass JournalEntry:\n entry_id: str\n date: date\n description: str\n lines: List[JournalLine]\n\n def __post_init__(self):\n if not isinstance(self.entry_id, str) or not self.entry_id.strip():\n raise ValidationError(\"entry_id must be a non-empty string\")\n if not isinstance(self.date, date):\n raise ValidationError(\"date must be a datetime.date\")\n if not isinstance(self.description, str):\n raise ValidationError(\"description must be a string\")\n if not isinstance(self.lines, list) or len(self.lines) < 2:\n raise ValidationError(\"a journal entry needs at least two lines\")\n for line in self.lines:\n if not isinstance(line, JournalLine):\n raise ValidationError(\"lines must be JournalLine instances\")\n debit_total = sum(\n (ln.amount for ln in self.lines if ln.side == \"debit\"), Decimal(\"0.00\")\n )\n credit_total = sum(\n (ln.amount for ln in self.lines if ln.side == \"credit\"), Decimal(\"0.00\")\n )\n if debit_total != credit_total:\n raise UnbalancedEntryError(\n f\"entry {self.entry_id} unbalanced: \"\n f\"debits {debit_total} != credits {credit_total}\"\n )\n\n\nclass Ledger:\n def __init__(self, accounts: List[Account]):\n if not accounts:\n raise ValidationError(\"ledger needs at least one account\")\n self._accounts: Dict[str, Account] = {}\n for acct in accounts:\n if not isinstance(acct, Account):\n raise ValidationError(\"chart entries must be Account instances\")\n if acct.code in self._accounts:\n raise ValidationError(f\"duplicate account code {acct.code}\")\n self._accounts[acct.code] = acct\n self._balances: Dict[str, Decimal] = {\n code: Decimal(\"0.00\") for code in self._accounts\n }\n self._posted_ids = set()\n self._last_date: Optional[date] = None\n\n def balance_of(self, code: str) -> Decimal:\n if code not in self._accounts:\n raise ValidationError(f\"unknown account code {code}\")\n return self._balances[code]\n\n def post(self, entry: JournalEntry) -> None:\n if not isinstance(entry, JournalEntry):\n raise ValidationError(\"only JournalEntry objects can be posted\")\n if entry.entry_id in self._posted_ids:\n raise ValidationError(f\"duplicate entry id {entry.entry_id}\")\n if self._last_date is not None and entry.date < self._last_date:\n raise ValidationError(\n f\"entry {entry.entry_id} dated {entry.date} is out of order \"\n f\"(last posted {self._last_date})\"\n )\n for line in entry.lines:\n if line.account not in self._accounts:\n raise ValidationError(\n f\"entry {entry.entry_id} references unknown account {line.account}\"\n )\n for line in entry.lines:\n signed = line.signed_amount()\n normal = self._accounts[line.account].normal_side\n if normal == \"debit\":\n self._balances[line.account] += signed\n else:\n self._balances[line.account] -= signed\n self._posted_ids.add(entry.entry_id)\n self._last_date = entry.date\n\n def trial_balance(self) -> Dict[str, Decimal]:\n debit_side_total = Decimal(\"0.00\")\n credit_side_total = Decimal(\"0.00\")\n report: Dict[str, Decimal] = {}\n for code in sorted(self._accounts):\n acct = self._accounts[code]\n bal = self._balances[code].quantize(CENT, rounding=ROUND_HALF_EVEN)\n report[code] = bal\n if acct.normal_side == \"debit\":\n debit_side_total += bal\n else:\n credit_side_total += bal\n if debit_side_total != credit_side_total:\n raise LedgerError(\n f\"trial balance mismatch: debits {debit_side_total} \"\n f\"!= credits {credit_side_total}\"\n )\n return report\n\n\nif __name__ == \"__main__\":\n chart = [\n Account(\"1000\", \"Cash\", \"debit\"),\n Account(\"2000\", \"Accounts Payable\", \"credit\"),\n Account(\"4000\", \"Sales Revenue\", \"credit\"),\n ]\n ledger = Ledger(chart)\n e1 = JournalEntry(\n \"E1\",\n date(2024, 1, 10),\n \"Cash sale\",\n [\n JournalLine(account=\"1000\", debit=\"500.00\"),\n JournalLine(account=\"4000\", credit=\"500.00\"),\n ],\n )\n ledger.post(e1)\n assert ledger.balance_of(\"1000\") == Decimal(\"500.00\")\n assert ledger.balance_of(\"4000\") == Decimal(\"500.00\")\n assert ledger.trial_balance() == {\n \"1000\": Decimal(\"500.00\"),\n \"2000\": Decimal(\"0.00\"),\n \"4000\": Decimal(\"500.00\"),\n }\n assert JournalLine(account=\"1000\", debit=\"12.345\").amount == Decimal(\"12.34\")\n assert JournalLine(account=\"1000\", debit=\"12.355\").amount == Decimal(\"12.36\")\n try:\n JournalEntry(\n \"E2\",\n date(2024, 1, 11),\n \"Bad entry\",\n [\n JournalLine(account=\"1000\", debit=\"100.00\"),\n JournalLine(account=\"4000\", credit=\"99.99\"),\n ],\n )\n except UnbalancedEntryError:\n pass\n else:\n raise AssertionError(\"expected UnbalancedEntryError\")\n print(\"all checks passed\")"}], "meta": {"idx": 2259, "topic": "accounting record dataclasses and schemas", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2701, "latency_s": 133.4}} +{"prompt": [{"role": "user", "content": "You are maintaining a small-business ledger and must compute VAT and sales tax for a list of line items, then produce a balanced invoice report. Each line item has a net amount (a string like '19.99'), a category, and a quantity. Category 'A' (standard goods) is subject to 10% sales tax and 5% VAT; category 'B' (food) is exempt from sales tax but subject to 5% VAT; category 'C' (exports) is exempt from both. For each line, compute line_net = net * quantity (exact Decimal), sales_tax = round_half_up(line_net * 0.10) for category 'A' only, vat = round_half_up(line_net * 0.05) for categories 'A' and 'B'. The line total is line_net + sales_tax + vat. The invoice total is the sum of all line totals, and the grand tax total is the sum of all sales_tax and vat amounts; the report must verify that sum(line_net) + grand_tax_total == invoice_total exactly. Use Decimal with ROUND_HALF_UP for all monetary rounding (taxes only; nets are exact). Input is a list of tuples (net, category, quantity). Example: [('19.99', 'A', 3), ('5.50', 'B', 2), ('120.00', 'C', 1)] should produce line totals of 68.97 (59.97 net + 6.00 sales tax + 3.00 VAT), 11.55, and 120.00, an invoice total of 200.52, and a grand tax total of 9.00. Write a function build_invoice(items) that returns a dict with keys 'lines' (list of dicts with line_net, sales_tax, vat, line_total), 'invoice_total', 'tax_total', and 'balanced' (True if the verification passes)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\nSALES_TAX_RATE = Decimal('0.10')\nVAT_RATE = Decimal('0.05')\n\n\ndef _round_half_up(value: Decimal) -> Decimal:\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef build_invoice(items):\n lines = []\n total_net = Decimal('0.00')\n total_tax = Decimal('0.00')\n invoice_total = Decimal('0.00')\n\n for net_str, category, quantity in items:\n net_unit = Decimal(net_str)\n line_net = net_unit * quantity\n sales_tax = Decimal('0.00')\n vat = Decimal('0.00')\n\n if category == 'A':\n sales_tax = _round_half_up(line_net * SALES_TAX_RATE)\n vat = _round_half_up(line_net * VAT_RATE)\n elif category == 'B':\n vat = _round_half_up(line_net * VAT_RATE)\n elif category == 'C':\n pass\n else:\n raise ValueError(f\"Unknown category: {category!r}\")\n\n line_total = line_net + sales_tax + vat\n lines.append({\n 'line_net': line_net,\n 'sales_tax': sales_tax,\n 'vat': vat,\n 'line_total': line_total,\n })\n total_net += line_net\n total_tax += sales_tax + vat\n invoice_total += line_total\n\n balanced = (total_net + total_tax) == invoice_total\n\n return {\n 'lines': lines,\n 'invoice_total': invoice_total,\n 'tax_total': total_tax,\n 'balanced': balanced,\n }\n\n\nif __name__ == '__main__':\n items = [('19.99', 'A', 3), ('5.50', 'B', 2), ('120.00', 'C', 1)]\n report = build_invoice(items)\n for line in report['lines']:\n print(line)\n print('Invoice total:', report['invoice_total'])\n print('Tax total:', report['tax_total'])\n print('Balanced:', report['balanced'])\n assert report['invoice_total'] == Decimal('200.52')\n assert report['tax_total'] == Decimal('9.00')\n assert report['balanced'] is True"}], "meta": {"idx": 2288, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 861, "latency_s": 20.5}} +{"prompt": [{"role": "user", "content": "Create a dataclass `LedgerEntry` representing a bookkeeping entry with fields: `date` (string 'YYYY-MM-DD'), `description` (string), `debit` (Decimal, default 0), `credit` (Decimal, default 0). Monetary amounts must use `decimal.Decimal` and be quantized to two decimal places with ROUND_HALF_UP rounding. Implement a function `validate_entry(entry)` that returns True if and only if the entry's debit and credit are both non-negative and at least one of them is greater than zero (i.e., the entry is not empty and not negative). Implement a function `ledger_total(entries)` that returns a tuple `(total_debits, total_credits, balance)` where totals are Decimals quantized to two places and `balance = total_debits - total_credits`. If any entry fails validation, raise `ValueError` with the message 'Invalid ledger entry'. Example: entries for a sale of 100.00 debit and a purchase of 40.555 credit (which rounds to 40.56) yield total_debits = 100.00, total_credits = 40.56, balance = 59.44."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import List, Tuple\n\n\nTWO_PLACES = Decimal('0.01')\n\n\ndef quantize(amount: Decimal) -> Decimal:\n return Decimal(amount).quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\n\n@dataclass\nclass LedgerEntry:\n date: str\n description: str\n debit: Decimal = Decimal('0.00')\n credit: Decimal = Decimal('0.00')\n\n def __post_init__(self):\n self.debit = quantize(self.debit)\n self.credit = quantize(self.credit)\n\n\ndef validate_entry(entry: LedgerEntry) -> bool:\n return (\n entry.debit >= 0\n and entry.credit >= 0\n and (entry.debit > 0 or entry.credit > 0)\n )\n\n\ndef ledger_total(entries: List[LedgerEntry]) -> Tuple[Decimal, Decimal, Decimal]:\n total_debits = Decimal('0.00')\n total_credits = Decimal('0.00')\n for entry in entries:\n if not validate_entry(entry):\n raise ValueError('Invalid ledger entry')\n total_debits += entry.debit\n total_credits += entry.credit\n total_debits = quantize(total_debits)\n total_credits = quantize(total_credits)\n balance = quantize(total_debits - total_credits)\n return total_debits, total_credits, balance\n\n\nif __name__ == '__main__':\n entries = [\n LedgerEntry('2024-01-05', 'Cash sale', debit=Decimal('100.00')),\n LedgerEntry('2024-01-06', 'Office supplies', credit=Decimal('40.555')),\n ]\n d, c, b = ledger_total(entries)\n assert (d, c, b) == (Decimal('100.00'), Decimal('40.56'), Decimal('59.44'))\n print(d, c, b)\n try:\n ledger_total([LedgerEntry('2024-01-07', 'Empty entry')])\n except ValueError as e:\n assert str(e) == 'Invalid ledger entry'\n print('All checks passed.')"}], "meta": {"idx": 2286, "topic": "accounting record dataclasses and schemas", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 709, "latency_s": 33.4}} +{"prompt": [{"role": "user", "content": "Write a function `inventory_valuation(purchases, units_sold)` that computes the ending inventory value and cost of goods sold (COGS) under three methods: FIFO, LIFO, and weighted average cost. `purchases` is a list of tuples `(units, unit_cost)` given in chronological order, where `unit_cost` is a string like '10.50' representing dollars; `units_sold` is an integer. Assume units_sold never exceeds total units purchased. All arithmetic must use Decimal with ROUND_HALF_UP rounding to cents. Return a dict with keys 'fifo', 'lifo', 'weighted_average', each mapping to a dict {'cogs': Decimal, 'ending_inventory': Decimal}. For the weighted average method, compute the average unit cost as total cost of all purchases divided by total units (rounded to cents with ROUND_HALF_UP), then use that single cost for both COGS and ending inventory. Example: purchases = [(100, '10.00'), (50, '12.00')], units_sold = 80. FIFO COGS = 800.00 (80 units at 10.00), ending inventory = 100*10.00 + 50*12.00 - 800.00 = 1300.00. LIFO COGS = 50*12.00 + 30*10.00 = 900.00, ending inventory = 1200.00. Weighted average: total cost 1600.00 / 150 units = 10.67, so COGS = 853.60 and ending inventory = 746.90."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef inventory_valuation(purchases, units_sold):\n lots = [(int(units), Decimal(str(cost))) for units, cost in purchases]\n total_units = sum(u for u, _ in lots)\n total_cost = sum((u * c for u, c in lots), Decimal('0'))\n\n def consume(reverse):\n remaining = units_sold\n cogs = Decimal('0')\n order = reversed(lots) if reverse else lots\n for units, cost in order:\n if remaining <= 0:\n break\n take = min(remaining, units)\n cogs += take * cost\n remaining -= take\n return cogs\n\n fifo_cogs = consume(reverse=False)\n lifo_cogs = consume(reverse=True)\n\n avg_cost = _round_cents(total_cost / total_units) if total_units else Decimal('0.00')\n wa_cogs = _round_cents(avg_cost * units_sold)\n\n return {\n 'fifo': {\n 'cogs': _round_cents(fifo_cogs),\n 'ending_inventory': _round_cents(total_cost - fifo_cogs),\n },\n 'lifo': {\n 'cogs': _round_cents(lifo_cogs),\n 'ending_inventory': _round_cents(total_cost - lifo_cogs),\n },\n 'weighted_average': {\n 'cogs': wa_cogs,\n 'ending_inventory': _round_cents(total_cost - wa_cogs),\n },\n }\n\n\nif __name__ == '__main__':\n result = inventory_valuation([(100, '10.00'), (50, '12.00')], 80)\n for method, values in result.items():\n print(method, values['cogs'], values['ending_inventory'])"}], "meta": {"idx": 2291, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 717, "latency_s": 8.2}} +{"prompt": [{"role": "user", "content": "Implement a function `inventory_valuation(transactions)` that processes a sequence of inventory transactions and computes, for each of three cost-flow assumptions \u2014 FIFO, LIFO, and perpetual moving weighted average \u2014 the total cost of goods sold (COGS), the ending inventory value, and the gross profit. Each transaction is a tuple `(\"BUY\", quantity, unit_cost)` or `(\"SELL\", quantity, unit_price)`; all money must be handled with `decimal.Decimal`, and each individual sale's COGS must be rounded to the nearest cent using `ROUND_HALF_UP`. Under the weighted-average method, keep the average unit cost unrounded internally, but deduct the rounded per-sale COGS from the cost pool so that `COGS + ending inventory == total purchase cost` holds exactly for every method. If a SELL would exceed the units on hand, raise `ValueError`. For example, `[(\"BUY\", 10, \"2.00\"), (\"BUY\", 10, \"3.00\"), (\"SELL\", 15, \"5.00\")]` must yield COGS of 35.00 (FIFO), 40.00 (LIFO), and 37.50 (weighted average), ending inventory of 15.00, 10.00, and 12.50 respectively, and gross profit of 40.00, 35.00, and 37.50 (revenue 75.00). Return a dict mapping the keys \"FIFO\", \"LIFO\", and \"WEIGHTED_AVERAGE\" each to a dict with string values under the keys \"cogs\", \"ending_inventory\", and \"gross_profit\", all formatted as two-decimal strings."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\ndef _money(x):\n \"\"\"Round a Decimal amount to the nearest cent (half-up).\"\"\"\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _normalize(transactions):\n \"\"\"Validate transactions; return (normalized_list, total_buy_cost, revenue).\"\"\"\n if transactions is None:\n raise ValueError(\"transactions must be a non-empty sequence\")\n txns = []\n on_hand = 0\n total_buy_cost = ZERO\n revenue = ZERO\n for t in transactions:\n if not isinstance(t, (tuple, list)) or len(t) != 3:\n raise ValueError(\"malformed transaction: %r\" % (t,))\n kind, qty, price = t\n kind = str(kind).upper()\n if kind not in (\"BUY\", \"SELL\"):\n raise ValueError(\"unknown transaction type: %r\" % (kind,))\n if isinstance(qty, bool) or not isinstance(qty, int) or qty <= 0:\n raise ValueError(\"quantity must be a positive integer: %r\" % (qty,))\n price = Decimal(str(price))\n if price <= 0:\n raise ValueError(\"price must be positive: %r\" % (price,))\n if kind == \"BUY\":\n on_hand += qty\n total_buy_cost += Decimal(qty) * price\n else:\n if qty > on_hand:\n raise ValueError(\n \"sell of %d units exceeds %d units on hand\" % (qty, on_hand)\n )\n on_hand -= qty\n revenue += Decimal(qty) * price\n txns.append((kind, qty, price))\n return txns, total_buy_cost, revenue\n\n\ndef _cogs_fifo(txns):\n lots = [] # list of [remaining_qty, unit_cost]; consume from the front\n cogs = ZERO\n for kind, qty, price in txns:\n if kind == \"BUY\":\n lots.append([qty, price])\n else:\n remaining = qty\n sale_cogs = Decimal(0)\n while remaining > 0:\n lot = lots[0]\n take = min(remaining, lot[0])\n sale_cogs += Decimal(take) * lot[1]\n lot[0] -= take\n remaining -= take\n if lot[0] == 0:\n lots.pop(0)\n cogs += _money(sale_cogs)\n return cogs\n\n\ndef _cogs_lifo(txns):\n lots = [] # stack of [remaining_qty, unit_cost]; consume from the top\n cogs = ZERO\n for kind, qty, price in txns:\n if kind == \"BUY\":\n lots.append([qty, price])\n else:\n remaining = qty\n sale_cogs = Decimal(0)\n while remaining > 0:\n lot = lots[-1]\n take = min(remaining, lot[0])\n sale_cogs += Decimal(take) * lot[1]\n lot[0] -= take\n remaining -= take\n if lot[0] == 0:\n lots.pop()\n cogs += _money(sale_cogs)\n return cogs\n\n\ndef _cogs_weighted_average(txns):\n pool = ZERO # total cost of units currently on hand\n qty_on_hand = 0\n cogs = ZERO\n for kind, qty, price in txns:\n if kind == \"BUY\":\n pool += Decimal(qty) * price\n qty_on_hand += qty\n else:\n avg = pool / Decimal(qty_on_hand) # unrounded moving average\n sale_cogs = _money(Decimal(qty) * avg)\n cogs += sale_cogs\n pool -= sale_cogs # deduct rounded COGS: keeps reconciliation exact\n qty_on_hand -= qty\n return cogs\n\n\n_METHODS = {\n \"FIFO\": _cogs_fifo,\n \"LIFO\": _cogs_lifo,\n \"WEIGHTED_AVERAGE\": _cogs_weighted_average,\n}\n\n\ndef inventory_valuation(transactions):\n \"\"\"Compute COGS, ending inventory, and gross profit under FIFO, LIFO,\n and perpetual moving weighted average.\n\n Returns {method: {\"cogs\": \"x.xx\", \"ending_inventory\": \"x.xx\",\n \"gross_profit\": \"x.xx\"}}.\n \"\"\"\n txns, total_buy_cost, revenue = _normalize(transactions)\n results = {}\n for name, fn in _METHODS.items():\n cogs = fn(txns)\n ending_inventory = total_buy_cost - cogs # exact reconciliation\n gross_profit = revenue - cogs\n results[name] = {\n \"cogs\": str(_money(cogs)),\n \"ending_inventory\": str(_money(ending_inventory)),\n \"gross_profit\": str(_money(gross_profit)),\n }\n return results\n\n\nif __name__ == \"__main__\":\n example = [\n (\"BUY\", 10, \"2.00\"),\n (\"BUY\", 10, \"3.00\"),\n (\"SELL\", 15, \"5.00\"),\n ]\n got = inventory_valuation(example)\n expected = {\n \"FIFO\": {\"cogs\": \"35.00\", \"ending_inventory\": \"15.00\", \"gross_profit\": \"40.00\"},\n \"LIFO\": {\"cogs\": \"40.00\", \"ending_inventory\": \"10.00\", \"gross_profit\": \"35.00\"},\n \"WEIGHTED_AVERAGE\": {\"cogs\": \"37.50\", \"ending_inventory\": \"12.50\", \"gross_profit\": \"37.50\"},\n }\n assert got == expected, got\n\n # Multi-sale scenario with exact reconciliation per method.\n txns = [\n (\"BUY\", 3, \"1.10\"),\n (\"BUY\", 7, \"2.03\"),\n (\"SELL\", 5, \"4.00\"),\n (\"BUY\", 4, \"1.99\"),\n (\"SELL\", 8, \"4.50\"),\n (\"SELL\", 1, \"5.00\"),\n ]\n res = inventory_valuation(txns)\n total_cost = Decimal(\"3\") * Decimal(\"1.10\") + Decimal(\"7\") * Decimal(\"2.03\") + Decimal(\"4\") * Decimal(\"1.99\")\n for m, d in res.items():\n assert Decimal(d[\"cogs\"]) + Decimal(d[\"ending_inventory\"]) == _money(total_cost), m\n\n # Overselling must raise.\n try:\n inventory_valuation([(\"BUY\", 2, \"1.00\"), (\"SELL\", 3, \"2.00\")])\n except ValueError:\n pass\n else:\n raise AssertionError(\"expected ValueError for oversell\")\n\n print(\"All checks passed.\")\n print(got)"}], "meta": {"idx": 2279, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1820, "latency_s": 94.6}} +{"prompt": [{"role": "user", "content": "Implement a mini general ledger supporting double-entry journal entries and percentage-based posting rules, using Decimal with cents quantized via ROUND_HALF_UP. A posting rule names one credit account and a list of (debit account, percentage) allocations whose percentages must sum to exactly 100%; when an entry applies a rule to an amount, each debit split (except the last) is rounded to cents half-up, and the final allocation receives the remainder so total debits equal the amount exactly. Manual entries list explicit (account, 'Dr'/'Cr', amount) lines. An entry must be rejected (and recorded as rejected with a reason) if it uses an unknown account or rule, contains a non-positive amount, has percentages that do not sum to 100%, or is unbalanced (total debits != total credits). After posting all entries, produce a trial balance showing each account's net balance (positive = debit, negative = credit) and verify the overall sum is zero. Worked example: accounts 1000 Cash, 2000 Wages Payable, 5010 Salaries, 5020 Benefits, 5030 Payroll Taxes; rule 'payroll' credits 2000 and debits 5010/40%, 5020/35%, 5030/25%. Entry JE-1 applies the rule to 99.99: 40% rounds to 40.00 and 35% rounds to 35.00, so the last allocation gets 99.99 - 75.00 = 24.99 (not the 25.00 that 25% would round to). Entry JE-2 is manual: Dr 1000 150.00, Cr 2000 150.00. Entry JE-3 is Dr 5010 10.00, Cr 2000 9.00 and must be rejected as unbalanced. The resulting trial balance is 1000: 150.00 Dr, 2000: 50.01 Cr, 5010: 40.00 Dr, 5020: 35.00 Dr, 5030: 24.99 Dr, with a net total of 0.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nONE = Decimal(\"1\")\nZERO = Decimal(\"0\")\n\n\ndef to_cents(value):\n \"\"\"Quantize a monetary value to cents using ROUND_HALF_UP.\"\"\"\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\nclass PostingError(Exception):\n \"\"\"Raised when a rule definition or journal entry is invalid.\"\"\"\n\n\nclass PostingRule:\n def __init__(self, name, credit_account, debit_allocations):\n self.name = name\n self.credit_account = credit_account\n self.debit_allocations = [(acct, Decimal(pct)) for acct, pct in debit_allocations]\n if not self.debit_allocations:\n raise PostingError(\"rule {!r}: at least one debit allocation is required\".format(name))\n total = sum((pct for _, pct in self.debit_allocations), ZERO)\n if total != ONE:\n raise PostingError(\n \"rule {!r}: percentages sum to {}, expected 1\".format(name, total)\n )\n for acct, pct in self.debit_allocations:\n if pct <= ZERO:\n raise PostingError(\n \"rule {!r}: percentage for {} must be positive\".format(name, acct)\n )\n\n\nclass Ledger:\n def __init__(self, account_names):\n self.accounts = dict(account_names)\n self.rules = {}\n self.posted = [] # list of (entry_id, [(account, side, Decimal amount)])\n self.rejected = [] # list of (entry_id, reason)\n\n def add_rule(self, rule):\n self.rules[rule.name] = rule\n\n def post(self, entry):\n eid = entry[\"id\"]\n try:\n lines = self._expand(entry)\n self._validate(lines)\n except PostingError as exc:\n self.rejected.append((eid, str(exc)))\n return False\n self.posted.append((eid, lines))\n return True\n\n def _expand(self, entry):\n if \"rule\" in entry:\n rule = self.rules.get(entry[\"rule\"])\n if rule is None:\n raise PostingError(\"unknown posting rule {!r}\".format(entry[\"rule\"]))\n amount = to_cents(entry[\"amount\"])\n if amount <= ZERO:\n raise PostingError(\"rule amount must be positive\")\n lines = []\n allocated = ZERO\n allocs = rule.debit_allocations\n for i, (acct, pct) in enumerate(allocs):\n if i == len(allocs) - 1:\n part = amount - allocated\n else:\n part = to_cents(amount * pct)\n allocated += part\n lines.append((acct, \"Dr\", part))\n lines.append((rule.credit_account, \"Cr\", amount))\n return lines\n lines = []\n for acct, side, amt in entry[\"lines\"]:\n lines.append((acct, side, Decimal(amt)))\n return lines\n\n def _validate(self, lines):\n if not lines:\n raise PostingError(\"entry has no lines\")\n dr_total = ZERO\n cr_total = ZERO\n for acct, side, amt in lines:\n if acct not in self.accounts:\n raise PostingError(\"unknown account {!r}\".format(acct))\n if side not in (\"Dr\", \"Cr\"):\n raise PostingError(\"invalid side {!r}\".format(side))\n if amt <= ZERO:\n raise PostingError(\"non-positive amount {} on account {}\".format(amt, acct))\n if side == \"Dr\":\n dr_total += amt\n else:\n cr_total += amt\n if dr_total != cr_total:\n raise PostingError(\"unbalanced: debits {} != credits {}\".format(dr_total, cr_total))\n\n def trial_balance(self):\n balances = {code: ZERO for code in self.accounts}\n for _, lines in self.posted:\n for acct, side, amt in lines:\n balances[acct] += amt if side == \"Dr\" else -amt\n return balances\n\n def format_trial_balance(self):\n balances = self.trial_balance()\n rows = []\n total = ZERO\n for code in sorted(balances):\n bal = balances[code]\n total += bal\n if bal > ZERO:\n side, amt = \"Dr\", bal\n elif bal < ZERO:\n side, amt = \"Cr\", -bal\n else:\n side, amt = \"-\", ZERO\n rows.append((code, self.accounts[code], amt, side))\n return rows, total\n\n\ndef main():\n accounts = {\n \"1000\": \"Cash\",\n \"2000\": \"Wages Payable\",\n \"5010\": \"Salaries Expense\",\n \"5020\": \"Benefits Expense\",\n \"5030\": \"Payroll Taxes Expense\",\n }\n ledger = Ledger(accounts)\n\n payroll = PostingRule(\n \"payroll\",\n \"2000\",\n [(\"5010\", \"0.40\"), (\"5020\", \"0.35\"), (\"5030\", \"0.25\")],\n )\n ledger.add_rule(payroll)\n\n entries = [\n {\"id\": \"JE-1\", \"rule\": \"payroll\", \"amount\": \"99.99\"},\n {\"id\": \"JE-2\", \"lines\": [(\"1000\", \"Dr\", \"150.00\"), (\"2000\", \"Cr\", \"150.00\")]},\n {\"id\": \"JE-3\", \"lines\": [(\"5010\", \"Dr\", \"10.00\"), (\"2000\", \"Cr\", \"9.00\")]},\n ]\n for entry in entries:\n ledger.post(entry)\n\n print(\"Journal lines of accepted entries:\")\n for eid, lines in ledger.posted:\n print(\" {}\".format(eid))\n for acct, side, amt in lines:\n print(\" {} {:>2} {:>10}\".format(acct, side, to_cents(amt)))\n\n print(\"\\nRejected entries:\")\n for eid, reason in ledger.rejected:\n print(\" {}: {}\".format(eid, reason))\n\n rows, total = ledger.format_trial_balance()\n print(\"\\nTrial balance:\")\n for code, name, amt, side in rows:\n print(\" {} {:<22} {:>10} {}\".format(code, name, to_cents(amt), side))\n print(\" Net total: {} (balanced: {})\".format(to_cents(total), total == ZERO))\n\n # Assertions for the worked example.\n je1_lines = ledger.posted[0][1]\n assert je1_lines == [\n (\"5010\", \"Dr\", Decimal(\"40.00\")),\n (\"5020\", \"Dr\", Decimal(\"35.00\")),\n (\"5030\", \"Dr\", Decimal(\"24.99\")),\n (\"2000\", \"Cr\", Decimal(\"99.99\")),\n ]\n assert ledger.rejected == [(\"JE-3\", \"unbalanced: debits 10.00 != credits 9.00\")]\n balances = ledger.trial_balance()\n assert balances[\"1000\"] == Decimal(\"150.00\")\n assert balances[\"2000\"] == Decimal(\"-50.01\")\n assert balances[\"5010\"] == Decimal(\"40.00\")\n assert balances[\"5020\"] == Decimal(\"35.00\")\n assert balances[\"5030\"] == Decimal(\"24.99\")\n assert sum(balances.values()) == ZERO\n print(\"\\nAll worked-example assertions passed.\")\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2280, "topic": "double-entry journal entries and posting rules", "difficulty": "hard", "provider": "novita", "in_tokens": 199, "out_tokens": 5703, "latency_s": 57.6}} +{"prompt": [{"role": "user", "content": "You are building a bookkeeping routine that prorates a single invoice total across several ledger cost centers, each with a non-negative weight. Write a function allocate(total, weights) that returns a list of Decimal amounts, one per cost center, such that (a) every amount is a multiple of one cent, (b) the amounts sum exactly to total, (c) each amount is within one cent of the exact proportional share total * weight / sum(weights), and (d) no amount is negative. Use the largest-remainder method: floor each exact share (in cents) with Decimal ROUND_FLOOR, then distribute the leftover cents one at a time to the shares with the largest fractional remainders, breaking ties by giving the cent to the lowest index first. Raise ValueError for empty weights, negative weights, a zero weight sum, a negative total, or a total with more than two decimal places. Worked example: allocate(Decimal('100.00'), [1, 2, 4]) must return [Decimal('14.29'), Decimal('28.57'), Decimal('57.14')], since the exact shares are 14.2857..., 28.5714..., 57.1428..., flooring gives 99.99, and the single leftover cent goes to the first share, which has the largest remainder."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_FLOOR\n\n\ndef allocate(total, weights):\n \"\"\"Prorate `total` across cost centers by `weights` using the\n largest-remainder method, guaranteeing cent-exact allocation.\"\"\"\n if not isinstance(total, Decimal):\n total = Decimal(str(total))\n weights = [w if isinstance(w, Decimal) else Decimal(str(w)) for w in weights]\n\n if not weights:\n raise ValueError(\"weights must be a non-empty sequence\")\n if any(w < 0 for w in weights):\n raise ValueError(\"weights must be non-negative\")\n if sum(weights) <= 0:\n raise ValueError(\"sum of weights must be positive\")\n if total < 0:\n raise ValueError(\"total must be non-negative\")\n cent = Decimal(\"0.01\")\n if total != total.quantize(cent):\n raise ValueError(\"total must have at most two decimal places\")\n\n weight_sum = sum(weights)\n\n # Work in integer cents to avoid any further rounding ambiguity.\n total_cents = int((total * 100).to_integral_value(rounding=ROUND_FLOOR))\n\n # Exact proportional shares, expressed in cents.\n exact_cents = [(total * w * 100) / weight_sum for w in weights]\n\n # Floor each share and record its fractional remainder.\n floor_cents = [int(e.to_integral_value(rounding=ROUND_FLOOR)) for e in exact_cents]\n remainders = [e - Decimal(f) for e, f in zip(exact_cents, floor_cents)]\n\n # Leftover cents to hand out.\n residual = total_cents - sum(floor_cents)\n\n # Largest remainder first; ties broken by lowest index.\n order = sorted(range(len(weights)), key=lambda i: (-remainders[i], i))\n\n result_cents = list(floor_cents)\n for i in order[:residual]:\n result_cents[i] += 1\n\n return [Decimal(c).quantize(cent) for c in result_cents]\n\n\nif __name__ == \"__main__\":\n result = allocate(Decimal(\"100.00\"), [1, 2, 4])\n print(result) # [Decimal('14.29'), Decimal('28.57'), Decimal('57.14')]\n assert result == [Decimal(\"14.29\"), Decimal(\"28.57\"), Decimal(\"57.14\")]\n assert sum(result) == Decimal(\"100.00\")\n\n result = allocate(Decimal(\"100.00\"), [1, 1, 1])\n print(result) # [Decimal('33.34'), Decimal('33.33'), Decimal('33.33')]\n assert result == [Decimal(\"33.34\"), Decimal(\"33.33\"), Decimal(\"33.33\")]\n assert sum(result) == Decimal(\"100.00\")\n\n # Zero-weight cost centers receive nothing.\n result = allocate(Decimal(\"10.01\"), [0, 1])\n print(result) # [Decimal('0.00'), Decimal('10.01')]\n assert result == [Decimal(\"0.00\"), Decimal(\"10.01\")]\n\n # Invalid inputs raise ValueError.\n for bad in (lambda: allocate(Decimal(\"1.00\"), []),\n lambda: allocate(Decimal(\"1.00\"), [1, -2]),\n lambda: allocate(Decimal(\"1.00\"), [0, 0]),\n lambda: allocate(Decimal(\"-1.00\"), [1]),\n lambda: allocate(Decimal(\"1.005\"), [1])):\n try:\n bad()\n raise AssertionError(\"expected ValueError\")\n except ValueError:\n pass\n print(\"All checks passed.\")"}], "meta": {"idx": 2290, "topic": "currency rounding rules with the Decimal type", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1077, "latency_s": 23.7}} +{"prompt": [{"role": "user", "content": "Implement a small double-entry ledger engine. Each journal entry has a date (ISO string), a memo, and two or more lines; each line has an account name and a Decimal amount, where debits are positive and credits are negative. A valid entry must balance: the sum of its lines must equal exactly 0 (using Decimal arithmetic, no tolerance). Implement `validate_entry(entry)` returning True/False, `post_entry(ledger, entry)` that validates and appends the entry to a ledger (a dict mapping account name to Decimal balance, creating accounts as needed, debits increasing and credits decreasing the balance), raising ValueError on an unbalanced entry, and `trial_balance(ledger)` returning a dict with 'total_debits' and 'total_credits' as Decimals, where total_debits is the sum of positive account balances and total_credits is the absolute sum of negative balances. Round each returned total to 2 decimal places with ROUND_HALF_UP. Example: entry with lines [('Cash', '100.00'), ('Revenue', '-100.00')] is valid; posting it gives ledger {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')} and trial_balance {'total_debits': Decimal('100.00'), 'total_credits': Decimal('100.00')}. An entry with lines [('Cash', '100.00'), ('Revenue', '-90.00')] is invalid and must raise ValueError when posted."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef validate_entry(entry):\n \"\"\"Return True if the journal entry balances exactly (sum of lines == 0).\"\"\"\n total = sum((line[1] for line in entry['lines']), Decimal('0'))\n return total == 0\n\n\ndef post_entry(ledger, entry):\n \"\"\"Validate the entry and post it to the ledger (dict of account -> Decimal).\n\n Raises ValueError if the entry does not balance.\n \"\"\"\n if not validate_entry(entry):\n raise ValueError(\n \"Journal entry '{}' on {} does not balance (sum of lines is not zero)\".format(\n entry.get('memo', ''), entry.get('date', '')\n )\n )\n for account, amount in entry['lines']:\n if not isinstance(amount, Decimal):\n amount = Decimal(str(amount))\n if account in ledger:\n ledger[account] += amount\n else:\n ledger[account] = amount\n return ledger\n\n\ndef trial_balance(ledger):\n \"\"\"Return {'total_debits': ..., 'total_credits': ...} rounded to 2 places (ROUND_HALF_UP).\"\"\"\n debits = Decimal('0')\n credits = Decimal('0')\n for balance in ledger.values():\n if balance > 0:\n debits += balance\n elif balance < 0:\n credits += -balance\n q = Decimal('0.01')\n return {\n 'total_debits': debits.quantize(q, rounding=ROUND_HALF_UP),\n 'total_credits': credits.quantize(q, rounding=ROUND_HALF_UP),\n }\n\n\nif __name__ == '__main__':\n ledger = {}\n entry1 = {\n 'date': '2024-01-15',\n 'memo': 'Cash sale',\n 'lines': [('Cash', Decimal('100.00')), ('Revenue', Decimal('-100.00'))],\n }\n assert validate_entry(entry1) is True\n post_entry(ledger, entry1)\n assert ledger == {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')}\n assert trial_balance(ledger) == {\n 'total_debits': Decimal('100.00'),\n 'total_credits': Decimal('100.00'),\n }\n\n bad_entry = {\n 'date': '2024-01-16',\n 'memo': 'Bad entry',\n 'lines': [('Cash', Decimal('100.00')), ('Revenue', Decimal('-90.00'))],\n }\n assert validate_entry(bad_entry) is False\n try:\n post_entry(ledger, bad_entry)\n raise AssertionError('expected ValueError')\n except ValueError:\n pass\n\n entry2 = {\n 'date': '2024-01-17',\n 'memo': 'Pay rent',\n 'lines': [\n ('Rent Expense', Decimal('60.55')),\n ('Bank Fee', Decimal('4.45')),\n ('Cash', Decimal('-65.00')),\n ],\n }\n post_entry(ledger, entry2)\n assert ledger['Cash'] == Decimal('35.00')\n tb = trial_balance(ledger)\n assert tb['total_debits'] == Decimal('165.00')\n assert tb['total_credits'] == Decimal('100.00')\n print('All tests passed.')"}], "meta": {"idx": 2293, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1048, "latency_s": 7.3}} +{"prompt": [{"role": "user", "content": "Implement a small invoice ledger system for a bookkeeping app. Each invoice line has a description, a quantity (Decimal), and a unit price (Decimal, dollars). The invoice total is the sum of quantity * unit_price per line, rounded to exactly 2 decimal places using ROUND_HALF_UP. Invoices are numbered with a prefix 'INV-', followed by a zero-padded 4-digit sequence number starting at 0001; the system must assign numbers automatically and never reuse a number, even if invoices are deleted. Implement three functions: create_invoice(lines) which takes a list of (description, quantity, unit_price) tuples and returns the invoice number string; get_invoice(invoice_number) which returns a dict with keys 'number', 'lines' (list of {'description', 'quantity', 'unit_price', 'amount'} with all monetary values as str of Decimals), and 'total' (str, 2 decimals); and parse_invoice_number(s) which validates a string and returns the integer sequence number, raising ValueError for anything not matching the exact pattern 'INV-' followed by 4 digits, or a number with leading zeros like 'INV-001' is fine but 'INV-0000' or 'INV-1' are invalid. Example: create_invoice([('Widget', Decimal('2.5'), Decimal('19.99')), ('Gadget', Decimal('1'), Decimal('0.005'))]) returns 'INV-0001' with total 19.99*2.5 + 0.005 = 49.9825 rounded to '49.98' (note 0.005*1 = 0.005, and 49.975 + 0.005 = 49.98 after ROUND_HALF_UP on 49.9825... verify: 2.5*19.99 = 49.975, plus 0.005 = 49.98 exactly, so total is '49.98'). parse_invoice_number('INV-0042') returns 42, while parse_invoice_number('INV-42') raises ValueError."}], "completion": [{"role": "assistant", "content": "import re\nfrom decimal import Decimal, ROUND_HALF_UP\n\n_CENTS = Decimal('0.01')\n_INVOICE_RE = re.compile(r'^INV-(\\d{4})$')\n\n_ledger = {}\n_next_seq = 1\n\n\ndef _to_money(value):\n return str(value.quantize(_CENTS, rounding=ROUND_HALF_UP))\n\n\ndef create_invoice(lines):\n global _next_seq\n number = 'INV-%04d' % _next_seq\n _next_seq += 1\n entries = []\n total = Decimal('0')\n for description, quantity, unit_price in lines:\n quantity = Decimal(str(quantity))\n unit_price = Decimal(str(unit_price))\n amount = quantity * unit_price\n total += amount\n entries.append({\n 'description': description,\n 'quantity': str(quantity),\n 'unit_price': str(unit_price),\n 'amount': str(amount),\n })\n _ledger[number] = {\n 'lines': entries,\n 'total': _to_money(total),\n }\n return number\n\n\ndef get_invoice(invoice_number):\n if invoice_number not in _ledger:\n raise KeyError('Unknown invoice: %s' % invoice_number)\n record = _ledger[invoice_number]\n return {\n 'number': invoice_number,\n 'lines': [dict(line) for line in record['lines']],\n 'total': record['total'],\n }\n\n\ndef parse_invoice_number(s):\n if not isinstance(s, str):\n raise ValueError('Invoice number must be a string')\n match = _INVOICE_RE.match(s)\n if not match:\n raise ValueError('Invalid invoice number: %r' % s)\n seq = int(match.group(1))\n if seq == 0:\n raise ValueError('Invalid invoice number: %r' % s)\n return seq\n\n\nif __name__ == '__main__':\n from decimal import Decimal as D\n num = create_invoice([('Widget', D('2.5'), D('19.99')), ('Gadget', D('1'), D('0.005'))])\n assert num == 'INV-0001'\n inv = get_invoice(num)\n assert inv['total'] == '49.98', inv['total']\n assert parse_invoice_number('INV-0042') == 42\n for bad in ('INV-42', 'INV-0000', 'inv-0042', 'INV-00421', 'XX-0042', ''):\n try:\n parse_invoice_number(bad)\n except ValueError:\n pass\n else:\n raise AssertionError('should have failed: %r' % bad)\n print('All checks passed.')"}], "meta": {"idx": 2294, "topic": "invoice generation, numbering, and parsing", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 967, "latency_s": 7.2}} +{"prompt": [{"role": "user", "content": "You are given a CSV file of bank transactions with columns: date,description,amount. Write a program that (1) parses the CSV, skipping a header row and any row that is blank or malformed (wrong column count, unparseable date in YYYY-MM-DD format, or non-numeric amount); (2) validates each amount using Decimal with exactly 2 decimal places \u2014 amounts with more than 2 decimal places are invalid and skipped; (3) treats positive amounts as debits (charges) and negative amounts as credits (refunds); (4) computes the opening balance of 0.00 and applies transactions in date order, ties broken by original file order, printing the running balance after each transaction to 2 decimal places; and (5) writes a valid export CSV to stdout with columns date,description,amount,balance, followed by a final summary line 'TOTAL_DEBITS ', 'TOTAL_CREDITS ', 'FINAL_BALANCE ' where credits are reported as positive sums. For example, input rows '2024-01-05,Coffee Shop,-4.50' and '2024-01-03,Payroll,1500.00' produce output rows in date order: '2024-01-03,Payroll,1500.00,1500.00' then '2024-01-05,Coffee Shop,-4.50,1495.50', then 'TOTAL_DEBITS 0.00', 'TOTAL_CREDITS 4.50', 'FINAL_BALANCE 1495.50'. Invalid rows like '2024-01-05,X,3.456' or 'bad-date,Y,1.00' must be silently skipped. Read the CSV from a file named transactions.csv in the current directory."}], "completion": [{"role": "assistant", "content": "import csv\nimport io\nfrom datetime import datetime\nfrom decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef q2(d):\n return d.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef parse_amount(text):\n try:\n value = Decimal(text.strip())\n except InvalidOperation:\n return None\n if not value.is_finite():\n return None\n if -value.as_tuple().exponent > 2:\n return None\n return q2(value)\n\n\ndef parse_date(text):\n try:\n datetime.strptime(text.strip(), '%Y-%m-%d')\n return text.strip()\n except ValueError:\n return None\n\n\ndef main():\n rows = []\n with open('transactions.csv', newline='', encoding='utf-8') as f:\n reader = csv.reader(f)\n for index, raw in enumerate(reader):\n if index == 0:\n continue\n if not raw or len(raw) != 3:\n continue\n date = parse_date(raw[0])\n if date is None:\n continue\n amount = parse_amount(raw[2])\n if amount is None:\n continue\n description = raw[1].strip()\n rows.append((date, index, description, amount))\n\n rows.sort(key=lambda r: (r[0], r[1]))\n\n out = io.StringIO()\n writer = csv.writer(out)\n writer.writerow(['date', 'description', 'amount', 'balance'])\n\n balance = Decimal('0.00')\n total_debits = Decimal('0.00')\n total_credits = Decimal('0.00')\n\n for date, _, description, amount in rows:\n balance = q2(balance + amount)\n if amount > 0:\n total_debits = q2(total_debits + amount)\n else:\n total_credits = q2(total_credits - amount)\n writer.writerow([date, description, f'{q2(amount):.2f}', f'{balance:.2f}'])\n\n print(out.getvalue().rstrip('\\n'))\n print(f'TOTAL_DEBITS {q2(total_debits):.2f}')\n print(f'TOTAL_CREDITS {q2(total_credits):.2f}')\n print(f'FINAL_BALANCE {q2(balance):.2f}')\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2284, "topic": "transaction CSV import, validation, and export", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 867, "latency_s": 62.2}} +{"prompt": [{"role": "user", "content": "You are given a list of transactions from a small business checking account, where each transaction is a tuple (date, description, amount). The amount is a Decimal representing a signed value: negative for money leaving the account, positive for money coming in. Write a function `find_suspicious(transactions)` that returns a list of descriptions of transactions considered suspicious, preserving the order they appear. A transaction is suspicious if it is a duplicate: a later transaction has the exact same date, description, and amount as an earlier one. Additionally, a transaction is suspicious if its amount is negative and its absolute value is greater than Decimal('5000.00'). Each description should appear only once in the result, even if multiple transactions share it. For example, given [('2024-01-05', 'Office rent', Decimal('-1200.00')), ('2024-01-05', 'Office rent', Decimal('-1200.00')), ('2024-01-07', 'Client payment', Decimal('300.00'))], the function returns ['Office rent'] because the second rent entry duplicates the first. Use exact Decimal comparisons; do not convert to float."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\ndef find_suspicious(transactions):\n seen = set()\n suspicious = []\n reported = set()\n for date, description, amount in transactions:\n is_dup = (date, description, amount) in seen\n is_large = amount < 0 and abs(amount) > Decimal('5000.00')\n if (is_dup or is_large) and description not in reported:\n suspicious.append(description)\n reported.add(description)\n seen.add((date, description, amount))\n return suspicious\n\nif __name__ == '__main__':\n txns = [\n ('2024-01-05', 'Office rent', Decimal('-1200.00')),\n ('2024-01-05', 'Office rent', Decimal('-1200.00')),\n ('2024-01-07', 'Client payment', Decimal('300.00')),\n ]\n print(find_suspicious(txns)) # ['Office rent']\n txns2 = [\n ('2024-02-01', 'Equipment purchase', Decimal('-7500.50')),\n ('2024-02-02', 'Supplier invoice', Decimal('-450.00')),\n ('2024-02-02', 'Supplier invoice', Decimal('-450.00')),\n ]\n print(find_suspicious(txns2)) # ['Equipment purchase', 'Supplier invoice']"}], "meta": {"idx": 2296, "topic": "detecting duplicate or anomalous transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 561, "latency_s": 5.4}} +{"prompt": [{"role": "user", "content": "Write a function `t_account_balance(entries)` that computes the balance of a T-account from a list of (side, amount) tuples, where side is 'debit' or 'credit' and amount is a string like '150.00'. Use Decimal for exact arithmetic and round the final result to 2 decimal places with ROUND_HALF_UP. The result should be a string formatted like 'D 250.00' if debits exceed credits, 'C 100.00' if credits exceed debits, or '0.00' if they are equal (with no side letter). Entries with an amount of '0.00' should be ignored. For example, t_account_balance([('debit', '150.00'), ('debit', '100.00'), ('credit', '75.00')]) must return 'D 175.00', and t_account_balance([('debit', '50.00'), ('credit', '50.00')]) must return '0.00'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef t_account_balance(entries):\n debits = Decimal('0')\n credits = Decimal('0')\n for side, amount in entries:\n amt = Decimal(amount)\n if amt == 0:\n continue\n if side == 'debit':\n debits += amt\n elif side == 'credit':\n credits += amt\n else:\n raise ValueError(\"side must be 'debit' or 'credit'\")\n diff = debits - credits\n diff = diff.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if diff > 0:\n return 'D ' + str(diff)\n if diff < 0:\n return 'C ' + str(-diff)\n return '0.00'\n\n\nif __name__ == '__main__':\n assert t_account_balance([('debit', '150.00'), ('debit', '100.00'), ('credit', '75.00')]) == 'D 175.00'\n assert t_account_balance([('debit', '50.00'), ('credit', '50.00')]) == '0.00'\n assert t_account_balance([('credit', '200.00'), ('debit', '50.00'), ('credit', '0.00')]) == 'C 150.00'\n print('All tests passed.')"}], "meta": {"idx": 2298, "topic": "general ledger and T-account operations", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 445, "latency_s": 4.6}} +{"prompt": [{"role": "user", "content": "Write a function `variance_report(budget, actual)` that compares a monthly budget to actual spending. Each input is a dict mapping expense category names to amounts given as strings (e.g. \"120.50\"). Return a dict mapping each category to a tuple (difference, status), where difference is the actual minus budget as a Decimal rounded to 2 places, and status is 'over' if actual exceeds budget, 'under' if actual is less, and 'on_target' if equal. Include every category that appears in either input; if a category is missing from one side, treat that side's amount as Decimal('0.00'). For example, budget = {'rent': '800.00', 'food': '250.00'} and actual = {'rent': '800.00', 'food': '310.75', 'utilities': '90.25'} should return {'rent': (Decimal('-0.00'), 'on_target'), 'food': (Decimal('60.75'), 'over'), 'utilities': (Decimal('90.25'), 'over')} \u2014 note that a zero difference must be reported as Decimal('0.00') with status 'on_target'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef variance_report(budget, actual):\n categories = set(budget) | set(actual)\n report = {}\n for cat in categories:\n b = Decimal(budget.get(cat, '0.00'))\n a = Decimal(actual.get(cat, '0.00'))\n diff = (a - b).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if diff > 0:\n status = 'over'\n elif diff < 0:\n status = 'under'\n else:\n status = 'on_target'\n diff = Decimal('0.00')\n report[cat] = (diff, status)\n return report\n\n\nif __name__ == '__main__':\n budget = {'rent': '800.00', 'food': '250.00'}\n actual = {'rent': '800.00', 'food': '310.75', 'utilities': '90.25'}\n result = variance_report(budget, actual)\n assert result == {\n 'rent': (Decimal('0.00'), 'on_target'),\n 'food': (Decimal('60.75'), 'over'),\n 'utilities': (Decimal('90.25'), 'over'),\n }\n print(result)"}], "meta": {"idx": 2299, "topic": "budget versus actual variance analysis", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 490, "latency_s": 4.0}} +{"prompt": [{"role": "user", "content": "A bookstore tracks inventory purchases and sales in a ledger. Implement a function `inventory_valuation(ledger)` that processes a list of transactions and returns the value of remaining inventory under three methods: FIFO, LIFO, and weighted average cost. Each transaction is a dict with keys 'type' ('purchase' or 'sale'), 'units' (int), and 'unit_cost' (Decimal, present only for purchases). Purchases add a cost layer; sales remove units and must never exceed available stock (if they do, raise ValueError). All monetary amounts must use Decimal with ROUND_HALF_UP quantization to 0.01 at the end only. The function returns a dict {'fifo': Decimal, 'lifo': Decimal, 'weighted_average': Decimal}. Weighted average uses the running average cost of all units on hand at the time of each sale. Example: ledger = [{'type':'purchase','units':10,'unit_cost':Decimal('5.00')},{'type':'purchase','units':10,'unit_cost':Decimal('7.00')},{'type':'sale','units':12}] returns {'fifo': Decimal('56.00'), 'lifo': Decimal('44.00'), 'weighted_average': Decimal('60.00')} because FIFO leaves 8 units at 7.00 (56.00), LIFO leaves 8 units at 5.00 plus 2 units at 7.00... wait, LIFO removes the 7.00 layer first leaving 10 at 5.00 and 2 at 7.00 = 64.00, so the correct expected output is {'fifo': Decimal('56.00'), 'lifo': Decimal('64.00'), 'weighted_average': Decimal('60.00')}, where weighted average cost per unit is 6.00 and 10 units remain."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef inventory_valuation(ledger):\n Q = Decimal('0.01')\n\n def q(x):\n return x.quantize(Q, rounding=ROUND_HALF_UP)\n\n # FIFO layers\n fifo_layers = []\n # LIFO layers\n lifo_layers = []\n # Weighted average state\n wa_units = 0\n wa_total_cost = Decimal('0')\n\n for entry in ledger:\n etype = entry['type']\n units = entry['units']\n if etype == 'purchase':\n cost = entry['unit_cost']\n fifo_layers.append([units, cost])\n lifo_layers.append([units, cost])\n wa_units += units\n wa_total_cost += cost * units\n elif etype == 'sale':\n # Check availability\n if units > sum(u for u, _ in fifo_layers):\n raise ValueError('Sale exceeds available stock')\n # FIFO removal\n remaining = units\n while remaining > 0:\n layer = fifo_layers[0]\n if layer[0] <= remaining:\n remaining -= layer[0]\n fifo_layers.pop(0)\n else:\n layer[0] -= remaining\n remaining = 0\n # LIFO removal\n remaining = units\n while remaining > 0:\n layer = lifo_layers[-1]\n if layer[0] <= remaining:\n remaining -= layer[0]\n lifo_layers.pop()\n else:\n layer[0] -= remaining\n remaining = 0\n # Weighted average removal\n avg = wa_total_cost / wa_units if wa_units else Decimal('0')\n wa_total_cost -= avg * units\n wa_units -= units\n else:\n raise ValueError('Unknown transaction type')\n\n fifo_value = sum(cost * u for u, cost in fifo_layers)\n lifo_value = sum(cost * u for u, cost in lifo_layers)\n wa_value = wa_total_cost\n\n return {\n 'fifo': q(fifo_value),\n 'lifo': q(lifo_value),\n 'weighted_average': q(wa_value),\n }\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n ledger = [\n {'type': 'purchase', 'units': 10, 'unit_cost': Decimal('5.00')},\n {'type': 'purchase', 'units': 10, 'unit_cost': Decimal('7.00')},\n {'type': 'sale', 'units': 12},\n ]\n print(inventory_valuation(ledger))"}], "meta": {"idx": 2297, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 975, "latency_s": 7.1}} +{"prompt": [{"role": "user", "content": "You maintain a simple ledger of transactions for a small shop. Each transaction is a dict with an 'id', a 'type' ('sale' or 'refund'), and an 'amount' (a Decimal representing dollars). A transaction may later be voided, meaning it must be fully reversed: a voided sale subtracts its amount from net sales, and a voided refund adds its amount back (since the refund money returned to the customer). Write a function `net_sales(transactions)` that takes a list of transaction dicts and returns the net sales as a Decimal, rounded to 2 decimal places with ROUND_HALF_UP. Net sales = total sale amounts - total refund amounts, but voided transactions must be excluded entirely, as if they never happened. For example, given transactions [{'id': 1, 'type': 'sale', 'amount': Decimal('25.00')}, {'id': 2, 'type': 'refund', 'amount': Decimal('10.50')}, {'id': 3, 'type': 'sale', 'amount': Decimal('5.25'), 'voided': True}], the function returns Decimal('14.50'), because the voided sale of 5.25 is excluded, leaving 25.00 - 10.50 = 14.50."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef net_sales(transactions):\n \"\"\"Compute net sales from a ledger, ignoring voided transactions.\n\n Net sales = sum of sale amounts - sum of refund amounts.\n Any transaction whose 'voided' flag is truthy is excluded entirely.\n The result is a Decimal rounded to 2 places with ROUND_HALF_UP.\n \"\"\"\n total = Decimal('0')\n for txn in transactions:\n if txn.get('voided'):\n continue\n amount = Decimal(str(txn['amount']))\n if txn['type'] == 'sale':\n total += amount\n elif txn['type'] == 'refund':\n total -= amount\n else:\n raise ValueError(\"Unknown transaction type: {!r}\".format(txn['type']))\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n txns = [\n {'id': 1, 'type': 'sale', 'amount': Decimal('25.00')},\n {'id': 2, 'type': 'refund', 'amount': Decimal('10.50')},\n {'id': 3, 'type': 'sale', 'amount': Decimal('5.25'), 'voided': True},\n ]\n result = net_sales(txns)\n assert result == Decimal('14.50'), result\n print(result)"}], "meta": {"idx": 2301, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 562, "latency_s": 5.5}} +{"prompt": [{"role": "user", "content": "A bookstore sells items that may be VAT-taxable or VAT-exempt (e.g., books are exempt, electronics are not). You are given a list of sales, each as a tuple (item_name, category, net_price_str, quantity), where net_price_str is a string like '19.99' representing the net unit price. Write a function `compute_vat_report(sales, vat_rate_str)` that returns a report as a dictionary mapping each category to a dictionary with keys 'net_total', 'vat', 'gross_total' (all Decimal, rounded to 2 places with ROUND_HALF_UP). VAT is computed per category on the net total (net_price * quantity, summed), at rate vat_rate_str (e.g., '0.20' for 20%); exempt categories are those whose name contains 'exempt'. Also return the overall grand gross total under key '__grand__'. Example: sales = [('Notebook','books_exempt','10.00',2), ('Radio','electronics','19.99',1)], vat_rate='0.20' => books_exempt: net 20.00, vat 0.00, gross 20.00; electronics: net 19.99, vat 4.00, gross 23.99; grand gross total 43.99."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef compute_vat_report(sales, vat_rate_str):\n vat_rate = Decimal(vat_rate_str)\n report = {}\n grand = Decimal('0')\n for item_name, category, net_price_str, quantity in sales:\n net_line = Decimal(net_price_str) * quantity\n if category not in report:\n report[category] = {'net_total': Decimal('0'), 'vat': Decimal('0'), 'gross_total': Decimal('0')}\n entry = report[category]\n entry['net_total'] += net_line\n for category, entry in report.items():\n net = entry['net_total'].quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if 'exempt' in category:\n vat = Decimal('0.00')\n else:\n vat = (entry['net_total'] * vat_rate).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n gross = (net + vat).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n report[category] = {'net_total': net, 'vat': vat, 'gross_total': gross}\n grand += gross\n report['__grand__'] = grand.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return report\n\nif __name__ == '__main__':\n sales = [('Notebook', 'books_exempt', '10.00', 2), ('Radio', 'electronics', '19.99', 1)]\n r = compute_vat_report(sales, '0.20')\n assert r['books_exempt'] == {'net_total': Decimal('20.00'), 'vat': Decimal('0.00'), 'gross_total': Decimal('20.00')}\n assert r['electronics'] == {'net_total': Decimal('19.99'), 'vat': Decimal('4.00'), 'gross_total': Decimal('23.99')}\n assert r['__grand__'] == Decimal('43.99')\n print(r)"}], "meta": {"idx": 2300, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 651, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "A small firm wants to schedule recurring monthly rent postings. Given a monthly rent amount (in cents-safe Decimal), a start date, and a number of months, generate the journal entries. Each monthly posting occurs on the same day-of-month as the start date; if that day does not exist in a month, use the last day of that month. Additionally, if the start date is not the first day of its month, the first posting must be prorated by actual days: rent_for_partial_month = monthly_rent * (days_remaining_including_start) / days_in_start_month, rounded half-up to 2 decimal places (CENT rounding). Each entry is a tuple (date, Decimal amount) and the debit total must equal the sum of amounts. Write a function `generate_rent_entries(monthly_rent, start_date, months)` that returns a list of (date, Decimal) tuples. Example: monthly_rent = Decimal('1200.00'), start_date = date(2024, 1, 15), months = 3. January has 31 days and 17 days remain (Jan 15-31 inclusive), so the first entry is 1200 * 17/31 = Decimal('658.06') on 2024-01-15; then full 1200.00 postings on 2024-02-15 and 2024-03-15. The expected output is [(date(2024,1,15), Decimal('658.06')), (date(2024,2,15), Decimal('1200.00')), (date(2024,3,15), Decimal('1200.00'))]. Use only the standard library (datetime, decimal)."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date, timedelta\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _add_months(d, n):\n \"\"\"Add n months to date d; clamp day to last day of target month.\"\"\"\n total = (d.year * 12 + d.month - 1) + n\n year, month_idx = divmod(total, 12)\n month = month_idx + 1\n last_day = calendar.monthrange(year, month)[1]\n return date(year, month, min(d.day, last_day))\n\n\ndef generate_rent_entries(monthly_rent, start_date, months):\n if months <= 0:\n return []\n monthly_rent = Decimal(monthly_rent)\n entries = []\n\n days_in_start_month = calendar.monthrange(start_date.year, start_date.month)[1]\n if start_date.day == 1:\n first_amount = monthly_rent\n else:\n days_remaining = days_in_start_month - start_date.day + 1\n first_amount = _round_cents(monthly_rent * Decimal(days_remaining) / Decimal(days_in_start_month))\n entries.append((start_date, _round_cents(first_amount)))\n\n for i in range(1, months):\n posting_date = _add_months(start_date, i)\n entries.append((posting_date, _round_cents(monthly_rent)))\n\n return entries\n\n\nif __name__ == '__main__':\n result = generate_rent_entries(Decimal('1200.00'), date(2024, 1, 15), 3)\n expected = [\n (date(2024, 1, 15), Decimal('658.06')),\n (date(2024, 2, 15), Decimal('1200.00')),\n (date(2024, 3, 15), Decimal('1200.00')),\n ]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2302, "topic": "recurring and calendar-based postings", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 734, "latency_s": 7.7}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, life, rate)` that produces a depreciation ledger for an asset. If `rate` is None, use straight-line depreciation: each year the depreciation expense is (cost - salvage) / life, rounded to the nearest cent with ROUND_HALF_UP, except the final year, which takes the remaining book value minus salvage so the asset ends exactly at salvage value. If `rate` is given (e.g. 0.40), use declining-balance depreciation: each year the expense is the current book value times the rate, rounded to the nearest cent, but never depreciate below salvage value; once book value reaches salvage, subsequent years have zero expense. The function should return a list of tuples (year, depreciation_expense, accumulated_depreciation, ending_book_value), using Decimal for all money values, for years 1 through `life`. Example: cost=Decimal('10000.00'), salvage=Decimal('1000.00'), life=5, rate=Decimal('0.40') gives year 1 expense 4000.00, accumulated 4000.00, ending book value 6000.00; year 2 expense 2400.00, accumulated 6400.00, ending book value 3600.00; and the schedule continues until book value reaches salvage 1000.00, after which expenses are 0.00 for remaining years."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _round_cent(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef depreciation_schedule(cost, salvage, life, rate=None):\n cost = Decimal(str(cost))\n salvage = Decimal(str(salvage))\n if rate is not None:\n rate = Decimal(str(rate))\n\n entries = []\n book_value = cost\n accumulated = Decimal('0.00')\n\n if rate is None:\n # Straight-line: equal amounts, final year adjusts to hit salvage.\n base = _round_cent((cost - salvage) / Decimal(life))\n for year in range(1, life + 1):\n if year < life:\n expense = base\n else:\n expense = book_value - salvage\n expense = _round_cent(expense)\n accumulated += expense\n book_value -= expense\n entries.append((year, expense, _round_cent(accumulated), _round_cent(book_value)))\n else:\n # Declining balance: never below salvage.\n for year in range(1, life + 1):\n if book_value <= salvage:\n expense = Decimal('0.00')\n else:\n expense = _round_cent(book_value * rate)\n if book_value - expense < salvage:\n expense = book_value - salvage\n accumulated += expense\n book_value -= expense\n entries.append((year, _round_cent(expense), _round_cent(accumulated), _round_cent(book_value)))\n\n return entries\n\n\nif __name__ == '__main__':\n for row in depreciation_schedule('10000.00', '1000.00', 5, '0.40'):\n print(row)\n print()\n for row in depreciation_schedule('10000.00', '1000.00', 5, None):\n print(row)"}], "meta": {"idx": 2292, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 752, "latency_s": 35.3}} +{"prompt": [{"role": "user", "content": "A small consultancy pays its sales agents a commission on each closed deal. Write a function `apply_commission(amount, rate)` that takes a deal amount (as a string, e.g. \"1250.00\") and a commission rate as a percentage (e.g. 7.5), and returns a tuple of two Decimals: (commission, net_amount_paid_to_agent), where net_amount_paid_to_agent = amount - commission. Use the `decimal` module and round both values to 2 decimal places with ROUND_HALF_UP so the books always balance to the cent. Additionally, write a function `split_three_way(amount)` that splits an amount into three equal shares, rounding each share to 2 decimal places with ROUND_HALF_UP, and returns a tuple (share_a, share_b, share_c) where the third share absorbs any leftover cent so the shares sum exactly to the original amount. For example, `apply_commission(\"100.00\", 7.5)` should return (Decimal('7.50'), Decimal('92.50')), and `split_three_way(\"100.00\")` should return (Decimal('33.33'), Decimal('33.33'), Decimal('33.34')) because 100.00 / 3 = 33.333... rounds to 33.33, and the remaining cent is assigned to the third share."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO_PLACES = Decimal(\"0.01\")\n\n\ndef _money(value):\n return value.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\n\ndef apply_commission(amount, rate):\n amount = Decimal(str(amount))\n rate = Decimal(str(rate))\n commission = _money(amount * rate / Decimal(\"100\"))\n net = _money(amount - commission)\n return commission, net\n\n\ndef split_three_way(amount):\n amount = Decimal(str(amount))\n share = _money(amount / Decimal(\"3\"))\n third = _money(amount - share - share)\n return share, share, third\n\n\nif __name__ == \"__main__\":\n assert apply_commission(\"100.00\", 7.5) == (Decimal(\"7.50\"), Decimal(\"92.50\"))\n assert split_three_way(\"100.00\") == (\n Decimal(\"33.33\"),\n Decimal(\"33.33\"),\n Decimal(\"33.34\"),\n )\n assert sum(split_three_way(\"10.00\")) == Decimal(\"10.00\")\n print(apply_commission(\"1250.00\", 7.5))\n print(split_three_way(\"100.00\"))"}], "meta": {"idx": 2305, "topic": "commission, tip, and percentage splits", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 536, "latency_s": 6.5}} +{"prompt": [{"role": "user", "content": "You are given a list of double-entry ledger entries, where each entry is a tuple (account, debit, credit) with Decimal amounts. Accounts are named with prefixes: 'asset:', 'liability:', 'equity:', 'income:', 'expense:'. Write a function summarize(entries) that returns a tuple (net_income, assets, liabilities, equity) as Decimals rounded to 2 places with ROUND_HALF_UP. Net income = total income - total expenses. The balance sheet must satisfy assets = liabilities + equity + net_income, so equity is the closing equity (opening equity plus net income). For each account, compute its balance: for asset/expense accounts balance = debit - credit, and for liability/equity/income accounts balance = credit - debit; then sum balances by category. Example: entries = [('asset:cash', D('100.00'), D('0')), ('equity:capital', D('0'), D('100.00'))] gives net_income 0.00, assets 100.00, liabilities 0.00, equity 100.00 (since assets = liabilities + equity + net_income holds). Another example: [('asset:cash','50','0'), ('income:sales','0','50'), ('expense:rent','20','0'), ('asset:cash','0','20')] gives net_income 30.00, assets 30.00, liabilities 0.00, equity 30.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nD = Decimal\n\n\ndef summarize(entries):\n prefixes = ('asset:', 'liability:', 'equity:', 'income:', 'expense:')\n balances = {p: D('0') for p in prefixes}\n\n for account, debit, credit in entries:\n debit = D(str(debit))\n credit = D(str(credit))\n matched = None\n for p in prefixes:\n if account.startswith(p):\n matched = p\n break\n if matched is None:\n raise ValueError('unknown account prefix: %r' % account)\n if matched in ('asset:', 'expense:'):\n balances[matched] += debit - credit\n else:\n balances[matched] += credit - debit\n\n net_income = balances['income:'] - balances['expense:']\n assets = balances['asset:']\n liabilities = balances['liability:']\n equity = balances['equity:'] + net_income\n\n q = D('0.01')\n r = lambda x: x.quantize(q, rounding=ROUND_HALF_UP)\n return (r(net_income), r(assets), r(liabilities), r(equity))\n\n\nif __name__ == '__main__':\n print(summarize([('asset:cash', D('100.00'), D('0')),\n ('equity:capital', D('0'), D('100.00'))]))\n print(summarize([('asset:cash', D('50'), D('0')),\n ('income:sales', D('0'), D('50')),\n ('expense:rent', D('20'), D('0')),\n ('asset:cash', D('0'), D('20'))]))"}], "meta": {"idx": 2306, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 657, "latency_s": 5.9}} +{"prompt": [{"role": "user", "content": "A company keeps its ledger in USD but makes purchases in EUR. Write a function `fx_gain_loss(purchases, eur_usd_rates)` that computes the FX gain or loss for each purchase. Each purchase is a tuple (name, eur_amount, purchase_rate), where purchase_rate is the EUR/USD rate applied when the purchase was recorded. eur_usd_rates is a dict mapping purchase name to the current closing EUR/USD rate. The USD value at purchase time is eur_amount * purchase_rate, and the current USD value is eur_amount * closing rate; the FX gain/loss is the difference (current minus original), rounded to 2 decimal places with ROUND_HALF_UP. Return a dict mapping purchase name to its FX gain/loss Decimal (positive = gain, negative = loss). Use Decimal arithmetic throughout. Example: purchases = [('widgets', Decimal('100.00'), Decimal('1.10'))], eur_usd_rates = {'widgets': Decimal('1.05')} -> {'widgets': Decimal('-5.00')} because the value dropped from 110.00 USD to 105.00 USD."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef fx_gain_loss(purchases, eur_usd_rates):\n result = {}\n two = Decimal('0.01')\n for name, eur_amount, purchase_rate in purchases:\n original_usd = eur_amount * purchase_rate\n current_usd = eur_amount * eur_usd_rates[name]\n gain_loss = (current_usd - original_usd).quantize(two, rounding=ROUND_HALF_UP)\n result[name] = gain_loss\n return result\n\nif __name__ == '__main__':\n purchases = [('widgets', Decimal('100.00'), Decimal('1.10'))]\n rates = {'widgets': Decimal('1.05')}\n print(fx_gain_loss(purchases, rates))"}], "meta": {"idx": 2304, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 403, "latency_s": 11.9}} +{"prompt": [{"role": "user", "content": "Implement `process_ledger(accounts, entries)` for a double-entry general ledger, using `decimal.Decimal` for all money arithmetic. `accounts` maps an account code to its type, one of 'ASSET', 'LIABILITY', 'EQUITY', 'REVENUE', 'EXPENSE'; each entry is a dict `{'ref': ..., 'lines': [(code, side, amount), ...]}` where side is 'DR' or 'CR' and amount is a string (or Decimal) that must be strictly positive and an exact multiple of one cent, or the literal 'AUTO' (at most one line per entry), meaning the balancing plug computed from the other lines. Reject an entry, recording `[ref, reason]`, using the first applicable reason from: 'too few lines' (fewer than 2 lines), 'unknown account', 'bad side', 'posting rule' (debiting a REVENUE account or crediting an EXPENSE account is forbidden), 'bad amount', 'multiple AUTO', 'bad plug' (the computed plug is not strictly positive), or 'unbalanced' (total debits do not equal total credits); lines are checked in order, and within a line the checks run in the order account, side, posting rule, amount. Post valid entries in order and return `{'posted': [refs...], 'rejected': [[ref, reason], ...], 'trial_balance': {code: [debits, credits, balance]}, 'net_income': str}` where the trial balance covers every defined account sorted by code with 2-decimal-place strings for total posted debits, total posted credits, and the balance expressed on the account's normal side (debits minus credits for ASSET/EXPENSE, credits minus debits otherwise; a negative balance means an abnormal balance), and net_income is total revenue balances minus total expense balances as a 2-decimal string. Worked example: accounts `{'100':'ASSET','200':'LIABILITY','300':'EQUITY','400':'REVENUE','500':'EXPENSE'}` with entries E1 `[('100','DR','100.00'),('300','CR','100.00')]`, E2 `[('500','DR','40.00'),('100','CR','40.00')]`, E3 `[('100','DR','60.50'),('400','CR','60.50')]`, E4 `[('100','DR','10.00'),('400','CR','9.99')]`, E5 `[('200','DR','25.00'),('100','CR','AUTO')]` yields posted `['E1','E2','E3','E5']`, rejected `[['E4','unbalanced']]`, trial_balance `{'100':['160.50','65.00','95.50'],'200':['25.00','0.00','-25.00'],'300':['0.00','100.00','100.00'],'400':['0.00','60.50','60.50'],'500':['40.00','0.00','40.00']}`, and net_income `'20.50'`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, InvalidOperation\n\nCENT = Decimal(\"0.01\")\n\n\ndef _parse_amount(raw):\n \"\"\"Return the amount as a Decimal in cents, or None if invalid.\"\"\"\n try:\n d = Decimal(str(raw))\n except (InvalidOperation, ValueError, TypeError):\n return None\n try:\n q = d.quantize(CENT)\n except InvalidOperation:\n return None\n if d != q or q <= 0:\n return None\n return q\n\n\ndef _fmt(d):\n return str(d.quantize(CENT))\n\n\ndef _validate(accounts, lines):\n \"\"\"Return (ok, parsed_lines, reason) for one journal entry.\"\"\"\n if len(lines) < 2:\n return False, None, \"too few lines\"\n\n parsed = []\n auto_index = None\n\n for line in lines:\n code, side, amount = line[0], line[1], line[2]\n\n if code not in accounts:\n return False, None, \"unknown account\"\n if side not in (\"DR\", \"CR\"):\n return False, None, \"bad side\"\n\n atype = accounts[code]\n if side == \"DR\" and atype == \"REVENUE\":\n return False, None, \"posting rule\"\n if side == \"CR\" and atype == \"EXPENSE\":\n return False, None, \"posting rule\"\n\n if amount == \"AUTO\":\n if auto_index is not None:\n return False, None, \"multiple AUTO\"\n auto_index = len(parsed)\n parsed.append([code, side, None])\n else:\n amt = _parse_amount(amount)\n if amt is None:\n return False, None, \"bad amount\"\n parsed.append([code, side, amt])\n\n dr_sum = sum(p[2] for p in parsed if p[1] == \"DR\" and p[2] is not None)\n cr_sum = sum(p[2] for p in parsed if p[1] == \"CR\" and p[2] is not None)\n\n if auto_index is not None:\n code, side, _ = parsed[auto_index]\n if side == \"DR\":\n plug = cr_sum - dr_sum\n else:\n plug = dr_sum - cr_sum\n if plug <= 0:\n return False, None, \"bad plug\"\n parsed[auto_index][2] = plug.quantize(CENT)\n elif dr_sum != cr_sum:\n return False, None, \"unbalanced\"\n\n return True, [tuple(p) for p in parsed], None\n\n\ndef process_ledger(accounts, entries):\n posted = []\n rejected = []\n\n dr_totals = {code: Decimal(\"0.00\") for code in accounts}\n cr_totals = {code: Decimal(\"0.00\") for code in accounts}\n\n for entry in entries:\n ref = entry.get(\"ref\")\n lines = entry.get(\"lines\", [])\n ok, parsed, reason = _validate(accounts, lines)\n if not ok:\n rejected.append([ref, reason])\n continue\n for code, side, amount in parsed:\n if side == \"DR\":\n dr_totals[code] += amount\n else:\n cr_totals[code] += amount\n posted.append(ref)\n\n trial_balance = {}\n revenue_balance = Decimal(\"0.00\")\n expense_balance = Decimal(\"0.00\")\n\n for code in sorted(accounts):\n atype = accounts[code]\n dr = dr_totals[code]\n cr = cr_totals[code]\n if atype in (\"ASSET\", \"EXPENSE\"):\n balance = dr - cr\n else:\n balance = cr - dr\n trial_balance[code] = [_fmt(dr), _fmt(cr), _fmt(balance)]\n if atype == \"REVENUE\":\n revenue_balance += cr - dr\n elif atype == \"EXPENSE\":\n expense_balance += dr - cr\n\n return {\n \"posted\": posted,\n \"rejected\": rejected,\n \"trial_balance\": trial_balance,\n \"net_income\": _fmt(revenue_balance - expense_balance),\n }\n\n\nif __name__ == \"__main__\":\n accounts = {\n \"100\": \"ASSET\",\n \"200\": \"LIABILITY\",\n \"300\": \"EQUITY\",\n \"400\": \"REVENUE\",\n \"500\": \"EXPENSE\",\n }\n entries = [\n {\"ref\": \"E1\", \"lines\": [(\"100\", \"DR\", \"100.00\"), (\"300\", \"CR\", \"100.00\")]},\n {\"ref\": \"E2\", \"lines\": [(\"500\", \"DR\", \"40.00\"), (\"100\", \"CR\", \"40.00\")]},\n {\"ref\": \"E3\", \"lines\": [(\"100\", \"DR\", \"60.50\"), (\"400\", \"CR\", \"60.50\")]},\n {\"ref\": \"E4\", \"lines\": [(\"100\", \"DR\", \"10.00\"), (\"400\", \"CR\", \"9.99\")]},\n {\"ref\": \"E5\", \"lines\": [(\"200\", \"DR\", \"25.00\"), (\"100\", \"CR\", \"AUTO\")]},\n ]\n result = process_ledger(accounts, entries)\n assert result[\"posted\"] == [\"E1\", \"E2\", \"E3\", \"E5\"]\n assert result[\"rejected\"] == [[\"E4\", \"unbalanced\"]]\n assert result[\"trial_balance\"] == {\n \"100\": [\"160.50\", \"65.00\", \"95.50\"],\n \"200\": [\"25.00\", \"0.00\", \"-25.00\"],\n \"300\": [\"0.00\", \"100.00\", \"100.00\"],\n \"400\": [\"0.00\", \"60.50\", \"60.50\"],\n \"500\": [\"40.00\", \"0.00\", \"40.00\"],\n }\n assert result[\"net_income\"] == \"20.50\"\n print(result)"}], "meta": {"idx": 2232, "topic": "double-entry journal entries and posting rules", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1820, "latency_s": 236.3}} +{"prompt": [{"role": "user", "content": "Write a function `reconcile(book_balance, statement_entries)` that reconciles a checkbook balance against a bank statement. `book_balance` is a string representing the ledger balance (e.g. '1500.00'), and `statement_entries` is a list of tuples `(date, description, amount_str)` where a positive amount is a deposit and a negative amount is a withdrawal. Compute the adjusted bank balance by applying each entry to the starting book balance using `Decimal` with two-decimal rounding (ROUND_HALF_UP), and return a list of strings for each entry in the form 'YYYY-MM-DD | description | running_balance' where running_balance is a Decimal quantized to two places. Additionally, return the final adjusted balance. Example: for book_balance '1500.00' and entries [('2024-01-05','Deposit','500.00'), ('2024-01-06','Rent','-1200.005')], the running balances are '2000.00' and '799.99' (since -1200.005 rounds to -1200.01, and 2000.00 - 1200.01 = 799.99), and the function returns (['2024-01-05 | Deposit | 2000.00', '2024-01-06 | Rent | 799.99'], Decimal('799.99'))."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef reconcile(book_balance, statement_entries):\n balance = Decimal(book_balance).quantize(TWO, rounding=ROUND_HALF_UP)\n lines = []\n for date, description, amount_str in statement_entries:\n amount = Decimal(amount_str).quantize(TWO, rounding=ROUND_HALF_UP)\n balance += amount\n balance = balance.quantize(TWO, rounding=ROUND_HALF_UP)\n lines.append('%s | %s | %s' % (date, description, balance))\n return lines, balance\n\nif __name__ == '__main__':\n lines, final = reconcile('1500.00', [\n ('2024-01-05', 'Deposit', '500.00'),\n ('2024-01-06', 'Rent', '-1200.005'),\n ])\n assert lines == ['2024-01-05 | Deposit | 2000.00', '2024-01-06 | Rent | 799.99']\n assert final == Decimal('799.99')\n print(lines, final)"}], "meta": {"idx": 2308, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 486, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "Write a function aging_report(invoices, payments, as_of) that builds combined accounts receivable (AR) and accounts payable (AP) aging reports. Each invoice is a dict {\"id\", \"type\" (\"ar\" or \"ap\"), \"counterparty\", \"amount\", \"due_date\"} where amount may be negative (a credit note), and each payment is {\"type\", \"counterparty\", \"date\", \"amount\"}. Payments dated on or before as_of are applied in chronological order, FIFO against that counterparty's open items of the same type (ordered by due_date, then id), partially filling each item; any leftover payment amount becomes \"unapplied\" cash for that (type, counterparty), and credit notes are never reduced by payments but age like ordinary invoices. Age every non-zero outstanding item by days past due = (as_of - due_date).days into buckets \"current\" (days <= 0), \"1-30\", \"31-60\", \"61-90\", \"90+\". Return a JSON-serializable dict with: bucket totals, grand total, and the payment-weighted average days overdue of positive overdue items (quantized to 2dp with ROUND_HALF_UP, or null) for each of AR and AP; net exposure per bucket (AR minus AP); unapplied balances for every counterparty that made a payment on or before as_of (including 0.00); and a per-counterparty breakdown. All money must be handled with Decimal and returned as 2dp strings. Worked example: as_of = date(2024,3,31); invoices = [{\"id\":\"INV-1\",\"type\":\"ar\",\"counterparty\":\"Acme\",\"amount\":\"1000.00\",\"due_date\":date(2024,1,15)}, {\"id\":\"INV-2\",\"type\":\"ar\",\"counterparty\":\"Acme\",\"amount\":\"250.00\",\"due_date\":date(2024,3,20)}, {\"id\":\"CRN-1\",\"type\":\"ar\",\"counterparty\":\"Acme\",\"amount\":\"-50.00\",\"due_date\":date(2024,4,10)}, {\"id\":\"BILL-1\",\"type\":\"ap\",\"counterparty\":\"Beta\",\"amount\":\"500.00\",\"due_date\":date(2024,2,28)}, {\"id\":\"BILL-2\",\"type\":\"ap\",\"counterparty\":\"Beta\",\"amount\":\"300.00\",\"due_date\":date(2024,4,15)}]; payments = [{\"type\":\"ar\",\"counterparty\":\"Acme\",\"date\":date(2024,2,1),\"amount\":\"400.00\"}, {\"type\":\"ar\",\"counterparty\":\"Acme\",\"date\":date(2024,3,10),\"amount\":\"300.00\"}, {\"type\":\"ap\",\"counterparty\":\"Beta\",\"date\":date(2024,3,5),\"amount\":\"500.00\"}]. The 700.00 of Acme payments reduce INV-1 to 300.00 outstanding (76 days overdue, bucket 61-90), INV-2 stays 250.00 (11 days, bucket 1-30), CRN-1 is -50.00 in current, and BILL-1 is fully paid so BILL-2's 300.00 is current AP; the result must be {\"as_of\":\"2024-03-31\",\"ar\":{\"current\":\"-50.00\",\"1-30\":\"250.00\",\"31-60\":\"0.00\",\"61-90\":\"300.00\",\"90+\":\"0.00\",\"total\":\"500.00\",\"weighted_avg_days_overdue\":\"46.45\"},\"ap\":{\"current\":\"300.00\",\"1-30\":\"0.00\",\"31-60\":\"0.00\",\"61-90\":\"0.00\",\"90+\":\"0.00\",\"total\":\"300.00\",\"weighted_avg_days_overdue\":null},\"net_by_bucket\":{\"current\":\"-350.00\",\"1-30\":\"250.00\",\"31-60\":\"0.00\",\"61-90\":\"300.00\",\"90+\":\"0.00\"},\"unapplied\":{\"ar\":{\"Acme\":\"0.00\"},\"ap\":{\"Beta\":\"0.00\"}},\"by_counterparty\":{\"ar\":{\"Acme\":{\"current\":\"-50.00\",\"1-30\":\"250.00\",\"31-60\":\"0.00\",\"61-90\":\"300.00\",\"90+\":\"0.00\",\"total\":\"500.00\"}},\"ap\":{\"Beta\":{\"current\":\"300.00\",\"1-30\":\"0.00\",\"31-60\":\"0.00\",\"61-90\":\"0.00\",\"90+\":\"0.00\",\"total\":\"300.00\"}}}}."}], "completion": [{"role": "assistant", "content": "import json\nfrom collections import defaultdict\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nBUCKETS = [\"current\", \"1-30\", \"31-60\", \"61-90\", \"90+\"]\n\n\ndef q(x):\n return Decimal(x).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef bucket_for(days):\n if days <= 0:\n return \"current\"\n if days <= 30:\n return \"1-30\"\n if days <= 60:\n return \"31-60\"\n if days <= 90:\n return \"61-90\"\n return \"90+\"\n\n\ndef aging_report(invoices, payments, as_of):\n by_key = defaultdict(list)\n for inv in invoices:\n rec = {\n \"id\": inv[\"id\"],\n \"type\": inv[\"type\"],\n \"counterparty\": inv[\"counterparty\"],\n \"due\": inv[\"due_date\"],\n \"outstanding\": Decimal(str(inv[\"amount\"])),\n }\n by_key[(rec[\"type\"], rec[\"counterparty\"])].append(rec)\n for lst in by_key.values():\n lst.sort(key=lambda r: (r[\"due\"], r[\"id\"]))\n\n unapplied = defaultdict(lambda: Decimal(\"0\"))\n paid_keys = set()\n for pay in sorted(payments, key=lambda p: p[\"date\"]):\n if pay[\"date\"] > as_of:\n continue\n key = (pay[\"type\"], pay[\"counterparty\"])\n paid_keys.add(key)\n remaining = Decimal(str(pay[\"amount\"]))\n for rec in by_key.get(key, []):\n if remaining <= 0:\n break\n if rec[\"outstanding\"] <= 0:\n continue\n applied = min(remaining, rec[\"outstanding\"])\n rec[\"outstanding\"] -= applied\n remaining -= applied\n if remaining > 0:\n unapplied[key] += remaining\n\n def empty_buckets():\n return {b: Decimal(\"0\") for b in BUCKETS}\n\n totals = {\"ar\": empty_buckets(), \"ap\": empty_buckets()}\n grand = {\"ar\": Decimal(\"0\"), \"ap\": Decimal(\"0\")}\n wsum = {\"ar\": Decimal(\"0\"), \"ap\": Decimal(\"0\")}\n wamt = {\"ar\": Decimal(\"0\"), \"ap\": Decimal(\"0\")}\n cp_tot = {\"ar\": defaultdict(empty_buckets), \"ap\": defaultdict(empty_buckets)}\n\n for (rec_type, cp), lst in by_key.items():\n for rec in lst:\n if rec[\"outstanding\"] == 0:\n continue\n days = (as_of - rec[\"due\"]).days\n b = bucket_for(days)\n totals[rec_type][b] += rec[\"outstanding\"]\n cp_tot[rec_type][cp][b] += rec[\"outstanding\"]\n grand[rec_type] += rec[\"outstanding\"]\n if days > 0 and rec[\"outstanding\"] > 0:\n wsum[rec_type] += rec[\"outstanding\"] * days\n wamt[rec_type] += rec[\"outstanding\"]\n\n def fmt_buckets(d):\n return {b: str(q(d[b])) for b in BUCKETS}\n\n def side(rec_type):\n out = fmt_buckets(totals[rec_type])\n out[\"total\"] = str(q(grand[rec_type]))\n if wamt[rec_type] > 0:\n out[\"weighted_avg_days_overdue\"] = str(q(wsum[rec_type] / wamt[rec_type]))\n else:\n out[\"weighted_avg_days_overdue\"] = None\n return out\n\n unap_out = {\"ar\": {}, \"ap\": {}}\n for t, cp in sorted(paid_keys):\n unap_out[t][cp] = str(q(unapplied.get((t, cp), Decimal(\"0\"))))\n\n by_cp = {}\n for rec_type in (\"ar\", \"ap\"):\n by_cp[rec_type] = {\n cp: {\n **fmt_buckets(bk),\n \"total\": str(q(sum(bk.values()))),\n }\n for cp, bk in sorted(cp_tot[rec_type].items())\n }\n\n return {\n \"as_of\": as_of.isoformat(),\n \"ar\": side(\"ar\"),\n \"ap\": side(\"ap\"),\n \"net_by_bucket\": {\n b: str(q(totals[\"ar\"][b] - totals[\"ap\"][b])) for b in BUCKETS\n },\n \"unapplied\": unap_out,\n \"by_counterparty\": by_cp,\n }\n\n\nif __name__ == \"__main__\":\n invoices = [\n {\"id\": \"INV-1\", \"type\": \"ar\", \"counterparty\": \"Acme\", \"amount\": \"1000.00\", \"due_date\": date(2024, 1, 15)},\n {\"id\": \"INV-2\", \"type\": \"ar\", \"counterparty\": \"Acme\", \"amount\": \"250.00\", \"due_date\": date(2024, 3, 20)},\n {\"id\": \"CRN-1\", \"type\": \"ar\", \"counterparty\": \"Acme\", \"amount\": \"-50.00\", \"due_date\": date(2024, 4, 10)},\n {\"id\": \"BILL-1\", \"type\": \"ap\", \"counterparty\": \"Beta\", \"amount\": \"500.00\", \"due_date\": date(2024, 2, 28)},\n {\"id\": \"BILL-2\", \"type\": \"ap\", \"counterparty\": \"Beta\", \"amount\": \"300.00\", \"due_date\": date(2024, 4, 15)},\n ]\n payments = [\n {\"type\": \"ar\", \"counterparty\": \"Acme\", \"date\": date(2024, 2, 1), \"amount\": \"400.00\"},\n {\"type\": \"ar\", \"counterparty\": \"Acme\", \"date\": date(2024, 3, 10), \"amount\": \"300.00\"},\n {\"type\": \"ap\", \"counterparty\": \"Beta\", \"date\": date(2024, 3, 5), \"amount\": \"500.00\"},\n ]\n report = aging_report(invoices, payments, date(2024, 3, 31))\n print(json.dumps(report, indent=2))"}], "meta": {"idx": 2281, "topic": "accounts receivable and payable aging reports", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2114, "latency_s": 127.1}} +{"prompt": [{"role": "user", "content": "You are preparing a monthly budget-vs-actual variance report. Each budget line is a tuple (category, budgeted_amount) and each actual ledger entry is a tuple (category, amount); amounts may be given as Decimal, int, or string, multiple entries per category must be summed, and expenses are positive numbers. For every category appearing in either list, define budget as the summed budget lines (0 if absent) and actual as the summed entries (0 if absent); the variance is budget minus actual, so a positive variance is favorable (under budget) and a negative variance is unfavorable. A variance is 'material' if its absolute value is at least material_abs OR its absolute value as a fraction of budget is at least material_pct (the percentage test only applies when budget is nonzero). All money must be handled with Decimal and each reported amount must be rounded to the nearest cent using ROUND_HALF_UP; the variance fraction must be reported rounded to 6 decimal places (or null when budget is zero). Return a list of dicts with keys category, budget, actual, variance, variance_fraction, favorable (bool), and material (bool), sorted by absolute variance descending with ties broken alphabetically by category. Example: budget_lines = [('Rent', '1200.00'), ('Supplies', '500.00')], actual_entries = [('Rent', '1180.00'), ('Supplies', '610.25'), ('Supplies', '15.00'), ('Marketing', '99.99')], material_abs = Decimal('25.00'), material_pct = Decimal('0.05') should return [{'category': 'Supplies', 'budget': '500.00', 'actual': '625.25', 'variance': '-125.25', 'variance_fraction': '-0.250500', 'favorable': False, 'material': True}, {'category': 'Marketing', 'budget': '0.00', 'actual': '99.99', 'variance': '-99.99', 'variance_fraction': None, 'favorable': False, 'material': True}, {'category': 'Rent', 'budget': '1200.00', 'actual': '1180.00', 'variance': '20.00', 'variance_fraction': '0.016667', 'favorable': True, 'material': False}] (Rent's 20.00 is below both thresholds; Marketing has zero budget so only the absolute test applies)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _to_decimal(value):\n \"\"\"Convert str/int/Decimal to Decimal without float contamination.\"\"\"\n if isinstance(value, Decimal):\n return value\n if isinstance(value, int):\n return Decimal(value)\n if isinstance(value, str):\n return Decimal(value.strip())\n raise TypeError(\"Unsupported amount type: %r\" % (type(value),))\n\n\ndef _cents(value):\n \"\"\"Quantize a Decimal to the nearest cent using ROUND_HALF_UP.\"\"\"\n return value.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP)\n\n\ndef variance_report(budget_lines, actual_entries, material_abs, material_pct):\n \"\"\"\n Build a budget-vs-actual variance report.\n\n budget_lines: iterable of (category, budgeted_amount)\n actual_entries: iterable of (category, actual_amount)\n material_abs: Decimal, absolute materiality threshold in currency units\n material_pct: Decimal, relative materiality threshold as a fraction of budget\n\n Returns a list of dicts sorted by absolute variance (descending),\n ties broken alphabetically by category.\n \"\"\"\n material_abs = _to_decimal(material_abs)\n material_pct = _to_decimal(material_pct)\n\n budgets = {}\n for category, amount in budget_lines:\n budgets[category] = budgets.get(category, Decimal(\"0\")) + _to_decimal(amount)\n\n actuals = {}\n for category, amount in actual_entries:\n actuals[category] = actuals.get(category, Decimal(\"0\")) + _to_decimal(amount)\n\n categories = set(budgets) | set(actuals)\n rows = []\n\n for category in categories:\n budget = budgets.get(category, Decimal(\"0\"))\n actual = actuals.get(category, Decimal(\"0\"))\n variance = budget - actual # positive = favorable (under budget)\n\n if budget != 0:\n fraction = variance / budget\n material = (\n abs(variance) >= material_abs\n or abs(fraction) >= material_pct\n )\n fraction_str = str(\n fraction.quantize(Decimal(\"0.000001\"), rounding=ROUND_HALF_UP)\n )\n else:\n material = abs(variance) >= material_abs\n fraction_str = None\n\n rows.append({\n \"category\": category,\n \"budget\": str(_cents(budget)),\n \"actual\": str(_cents(actual)),\n \"variance\": str(_cents(variance)),\n \"variance_fraction\": fraction_str,\n \"favorable\": variance > 0,\n \"material\": material,\n \"_sort_abs\": abs(variance),\n })\n\n rows.sort(key=lambda r: (-r[\"_sort_abs\"], r[\"category\"]))\n for row in rows:\n del row[\"_sort_abs\"]\n\n return rows\n\n\nif __name__ == \"__main__\":\n budget_lines = [(\"Rent\", \"1200.00\"), (\"Supplies\", \"500.00\")]\n actual_entries = [\n (\"Rent\", \"1180.00\"),\n (\"Supplies\", \"610.25\"),\n (\"Supplies\", \"15.00\"),\n (\"Marketing\", \"99.99\"),\n ]\n report = variance_report(\n budget_lines,\n actual_entries,\n material_abs=Decimal(\"25.00\"),\n material_pct=Decimal(\"0.05\"),\n )\n for row in report:\n print(row)"}], "meta": {"idx": 2303, "topic": "budget versus actual variance analysis", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1341, "latency_s": 19.4}} +{"prompt": [{"role": "user", "content": "An accounting firm needs a revenue-recognition engine for prepaid contracts, with a fiscal year that may start in any month. Implement four functions using only the standard library: (1) month_end(year, month) returning a datetime.date for the last calendar day of that month; (2) fiscal_quarter(d, fy_start_month) returning a tuple (fy_label, quarter) where fy_label is the calendar year in which the fiscal year ends and quarter is 1-4 (e.g., with fy_start_month=7, 2024-08-15 falls in FY2025 Q1, and 2025-01-15 in FY2025 Q3); (3) allocate(amount, start, end) which spreads a Decimal amount (given to the cent, non-negative) evenly per calendar day across a service period, splitting it by calendar month, rounding each month to cents with ROUND_HALF_UP, and applying the largest-remainder method (distributing leftover cents to the months with the largest fractional remainders, breaking ties in favor of the earlier month) so the monthly amounts sum exactly to the total; (4) quarterly_report(allocations, fy_start_month) which groups the monthly amounts (keyed by the first day of each month-segment) into fiscal quarters, returning a list sorted by (fy_label, quarter) where each entry has a string label like 'FY2025Q1', the list of month-end dates, the quarter's recognized total, and the cumulative total. Worked example: allocate(Decimal('10000.00'), date(2024,7,1), date(2025,6,30)) yields Jul=849.32, Aug=849.32, Sep=821.92, Oct=849.32, Nov=821.92, Dec=849.31, Jan=849.31, Feb=767.12, Mar=849.31, Apr=821.92, May=849.31, Jun=821.92 (summing exactly to 10000.00), and quarterly_report with fy_start_month=7 gives recognized totals of 2520.56, 2520.55, 2465.74, 2493.15 with a final cumulative of 10000.00."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date, timedelta\nfrom decimal import Decimal, ROUND_HALF_UP, ROUND_FLOOR\n\nCENT = Decimal(\"0.01\")\n\n\ndef month_end(year, month):\n \"\"\"Last calendar day of the given month as a datetime.date.\"\"\"\n return date(year, month, calendar.monthrange(year, month)[1])\n\n\ndef fiscal_quarter(d, fy_start_month):\n \"\"\"Return (fy_label, quarter) where fy_label is the calendar year in\n which the fiscal year containing d ends, and quarter is 1-4.\"\"\"\n if not 1 <= fy_start_month <= 12:\n raise ValueError(\"fy_start_month must be in 1..12\")\n offset = (d.month - fy_start_month) % 12 # 0-based month within fiscal year\n quarter = offset // 3 + 1\n fy_label = d.year + (1 if d.month >= fy_start_month else 0)\n return fy_label, quarter\n\n\ndef allocate(amount, start, end):\n \"\"\"Spread `amount` (Decimal, whole cents, >= 0) evenly per calendar day\n over [start, end], split by calendar month, rounded to cents with\n ROUND_HALF_UP plus largest-remainder adjustment (earlier month wins ties),\n so the monthly amounts sum exactly to `amount`.\n Returns dict mapping each month-segment's first date -> Decimal cents.\"\"\"\n if start > end:\n raise ValueError(\"start must not be after end\")\n if amount < 0:\n raise ValueError(\"amount must be non-negative\")\n total_cents = (amount / CENT)\n if total_cents != total_cents.to_integral_value():\n raise ValueError(\"amount must be specified to the cent\")\n total_cents = total_cents.to_integral_value(rounding=ROUND_HALF_UP)\n\n # Split the period into per-month segments: (segment_start, days).\n segments = []\n cur = start\n while cur <= end:\n seg_end = min(end, month_end(cur.year, cur.month))\n days = (seg_end - cur).days + 1\n segments.append((cur, days))\n cur = seg_end + timedelta(days=1)\n\n total_days = sum(days for _, days in segments)\n if total_days == 0 or total_cents == 0:\n return {seg_start: Decimal(\"0.00\") for seg_start, _ in segments}\n\n # Exact per-month share in cents, floored; track fractional remainders.\n cents_map = {}\n remainders = []\n floor_sum = Decimal(0)\n for seg_start, days in segments:\n exact = total_cents * days / total_days\n fl = exact.to_integral_value(rounding=ROUND_FLOOR)\n cents_map[seg_start] = fl\n remainders.append((exact - fl, seg_start))\n floor_sum += fl\n\n leftover = int(total_cents - floor_sum)\n # Largest remainder first; tie-break by earlier segment start.\n remainders.sort(key=lambda t: (-t[0], t[1]))\n for i in range(leftover):\n cents_map[remainders[i][1]] += 1\n\n return {seg_start: (cents_map[seg_start] * CENT).quantize(CENT, rounding=ROUND_HALF_UP)\n for seg_start, _ in segments}\n\n\ndef quarterly_report(allocations, fy_start_month):\n \"\"\"Group monthly allocations into fiscal quarters.\n Each entry: label, month_ends (dates), recognized, cumulative.\"\"\"\n grouped = {}\n for seg_start, amt in allocations.items():\n key = fiscal_quarter(seg_start, fy_start_month)\n grouped.setdefault(key, []).append((seg_start, amt))\n\n report = []\n cumulative = Decimal(\"0.00\")\n for (fy_label, quarter) in sorted(grouped):\n entries = sorted(grouped[(fy_label, quarter)])\n recognized = sum((amt for _, amt in entries), Decimal(\"0.00\"))\n cumulative += recognized\n month_ends = [month_end(s.year, s.month) for s, _ in entries]\n report.append({\n \"label\": \"FY{}Q{}\".format(fy_label, quarter),\n \"fiscal_year\": fy_label,\n \"quarter\": quarter,\n \"month_ends\": month_ends,\n \"recognized\": recognized.quantize(CENT, rounding=ROUND_HALF_UP),\n \"cumulative\": cumulative.quantize(CENT, rounding=ROUND_HALF_UP),\n })\n return report\n\n\nif __name__ == \"__main__\":\n # Month-end utility checks\n assert month_end(2024, 2) == date(2024, 2, 29) # leap year\n assert month_end(2025, 2) == date(2025, 2, 28)\n assert month_end(2024, 12) == date(2024, 12, 31)\n\n # Fiscal quarter checks (fiscal year starts in July)\n assert fiscal_quarter(date(2024, 8, 15), 7) == (2025, 1)\n assert fiscal_quarter(date(2025, 1, 15), 7) == (2025, 3)\n assert fiscal_quarter(date(2025, 6, 30), 7) == (2025, 4)\n assert fiscal_quarter(date(2024, 3, 31), 1) == (2024, 1)\n\n # Worked example: 10000.00 over 2024-07-01 .. 2025-06-30 (365 days)\n amount = Decimal(\"10000.00\")\n allocs = allocate(amount, date(2024, 7, 1), date(2025, 6, 30))\n expected = {\n date(2024, 7, 1): \"849.32\", date(2024, 8, 1): \"849.32\",\n date(2024, 9, 1): \"821.92\", date(2024, 10, 1): \"849.32\",\n date(2024, 11, 1): \"821.92\", date(2024, 12, 1): \"849.31\",\n date(2025, 1, 1): \"849.31\", date(2025, 2, 1): \"767.12\",\n date(2025, 3, 1): \"849.31\", date(2025, 4, 1): \"821.92\",\n date(2025, 5, 1): \"849.31\", date(2025, 6, 1): \"821.92\",\n }\n for d, s in expected.items():\n assert allocs[d] == Decimal(s), (d, allocs[d])\n assert sum(allocs.values()) == amount # exact, no rounding drift\n\n rep = quarterly_report(allocs, 7)\n assert [r[\"label\"] for r in rep] == [\"FY2025Q1\", \"FY2025Q2\", \"FY2025Q3\", \"FY2025Q4\"]\n assert [r[\"recognized\"] for r in rep] == [\n Decimal(\"2520.56\"), Decimal(\"2520.55\"), Decimal(\"2465.74\"), Decimal(\"2493.15\")]\n assert rep[-1][\"cumulative\"] == amount\n assert rep[0][\"month_ends\"] == [date(2024, 7, 31), date(2024, 8, 31), date(2024, 9, 30)]\n\n # Edge cases: single-day period and mid-month start still balance exactly\n one_day = allocate(Decimal(\"99.99\"), date(2025, 3, 17), date(2025, 3, 17))\n assert one_day[date(2025, 3, 17)] == Decimal(\"99.99\")\n partial = allocate(Decimal(\"1000.00\"), date(2025, 1, 16), date(2025, 3, 15))\n assert sum(partial.values()) == Decimal(\"1000.00\")\n assert len(partial) == 3 # Jan (16 days), Feb (28), Mar (15)\n\n for r in rep:\n print(r[\"label\"], [d.isoformat() for d in r[\"month_ends\"]],\n r[\"recognized\"], r[\"cumulative\"])\n print(\"All checks passed.\")"}], "meta": {"idx": 2295, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2030, "latency_s": 40.7}} +{"prompt": [{"role": "user", "content": "Write a function `t_account_balance(entries)` that simulates a general ledger T-account. Each entry is a tuple `(side, amount)` where `side` is either `'debit'` or `'credit'` and `amount` is a monetary value given as a string (e.g. `'120.50'`). The function must use `decimal.Decimal` for exact arithmetic, sum debits and credits separately, and return a tuple `(balance, side)` where `balance` is the net amount quantized to 2 decimal places (ROUND_HALF_UP) and `side` is `'debit'` if debits exceed credits, `'credit'` if credits exceed debits, or `'balanced'` if they are equal. For example, given `[('debit', '100.00'), ('credit', '45.50'), ('debit', '25.00')]`, the debits total 125.00, credits total 45.50, so the result is `(Decimal('79.50'), 'debit')`. Raise a `ValueError` if any side is invalid or any amount is not a valid decimal."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n\n\ndef t_account_balance(entries):\n debits = Decimal('0')\n credits = Decimal('0')\n for side, amount in entries:\n if side not in ('debit', 'credit'):\n raise ValueError(f\"Invalid side: {side!r}\")\n try:\n amt = Decimal(str(amount))\n except InvalidOperation:\n raise ValueError(f\"Invalid amount: {amount!r}\")\n if side == 'debit':\n debits += amt\n else:\n credits += amt\n balance = (debits - credits).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if balance > 0:\n return (balance, 'debit')\n if balance < 0:\n return (-balance, 'credit')\n return (balance, 'balanced')\n\n\nif __name__ == '__main__':\n result = t_account_balance(\n [('debit', '100.00'), ('credit', '45.50'), ('debit', '25.00')]\n )\n print(result) # (Decimal('79.50'), 'debit')"}], "meta": {"idx": 2311, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 462, "latency_s": 9.7}} +{"prompt": [{"role": "user", "content": "Write a function `summarize_ledger(entries)` that turns a list of bookkeeping entries into a simple financial report. Each entry is a tuple `(date, account, debit, credit)` where `debit` and `credit` are strings representing decimal money amounts (e.g. '150.00'), and exactly one of them may be '0.00' (entries are single-sided; a balanced transaction appears as two separate entries). Accounts starting with '1' are assets, '2' are liabilities, '3' is equity, '4' is revenue, and '5' is expenses. For each account, compute its net debit balance (total debits minus total credits) using `Decimal` arithmetic with ROUND_HALF_UP, quantized to 2 decimal places. Then produce a report as a dict with keys: 'total_revenue' (sum of net credit balances of revenue accounts, i.e. negated net debit balances), 'total_expenses' (sum of net debit balances of expense accounts), 'net_income' (total_revenue minus total_expenses), 'total_assets' (sum of net debit balances of asset accounts), 'total_liabilities' (sum of net credit balances of liability accounts, negated), 'total_equity' (sum of net credit balances of equity accounts, negated). All values must be Decimal quantized to 2 places. Example: entries = [('2024-01-01','1000 Cash','500.00','0.00'), ('2024-01-01','3000 Capital','0.00','500.00'), ('2024-01-02','4000 Sales','0.00','200.00'), ('2024-01-02','1000 Cash','200.00','0.00'), ('2024-01-03','5100 Rent','50.00','0.00'), ('2024-01-03','1000 Cash','0.00','50.00')] should return {'total_revenue': Decimal('200.00'), 'total_expenses': Decimal('50.00'), 'net_income': Decimal('150.00'), 'total_assets': Decimal('650.00'), 'total_liabilities': Decimal('0.00'), 'total_equity': Decimal('500.00')}. The balance check total_assets == total_liabilities + total_equity + net_income should hold."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\n\ndef summarize_ledger(entries):\n balances = defaultdict(lambda: Decimal('0'))\n for date, account, debit, credit in entries:\n d = Decimal(debit)\n c = Decimal(credit)\n balances[account] += d - c\n\n q = Decimal('0.01')\n def q2(x):\n return x.quantize(q, rounding=ROUND_HALF_UP)\n\n total_revenue = Decimal('0')\n total_expenses = Decimal('0')\n total_assets = Decimal('0')\n total_liabilities = Decimal('0')\n total_equity = Decimal('0')\n\n for account, bal in balances.items():\n code = account.split()[0]\n if code.startswith('4'):\n total_revenue += -bal\n elif code.startswith('5'):\n total_expenses += bal\n elif code.startswith('1'):\n total_assets += bal\n elif code.startswith('2'):\n total_liabilities += -bal\n elif code.startswith('3'):\n total_equity += -bal\n\n net_income = total_revenue - total_expenses\n return {\n 'total_revenue': q2(total_revenue),\n 'total_expenses': q2(total_expenses),\n 'net_income': q2(net_income),\n 'total_assets': q2(total_assets),\n 'total_liabilities': q2(total_liabilities),\n 'total_equity': q2(total_equity),\n }\n\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-01', '1000 Cash', '500.00', '0.00'),\n ('2024-01-01', '3000 Capital', '0.00', '500.00'),\n ('2024-01-02', '4000 Sales', '0.00', '200.00'),\n ('2024-01-02', '1000 Cash', '200.00', '0.00'),\n ('2024-01-03', '5100 Rent', '50.00', '0.00'),\n ('2024-01-03', '1000 Cash', '0.00', '50.00'),\n ]\n report = summarize_ledger(entries)\n print(report)\n assert report == {\n 'total_revenue': Decimal('200.00'),\n 'total_expenses': Decimal('50.00'),\n 'net_income': Decimal('150.00'),\n 'total_assets': Decimal('650.00'),\n 'total_liabilities': Decimal('0.00'),\n 'total_equity': Decimal('500.00'),\n }\n assert report['total_assets'] == report['total_liabilities'] + report['total_equity'] + report['net_income']"}], "meta": {"idx": 2313, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1012, "latency_s": 18.1}} +{"prompt": [{"role": "user", "content": "Write a function `find_suspicious(entries, tolerance)` that inspects a ledger of transactions for duplicates and anomalies. Each entry is a tuple `(date, description, amount)` where `date` is a string 'YYYY-MM-DD', `description` is a string, and `amount` is a string representing a monetary value (use `Decimal` for all arithmetic). A transaction is a 'duplicate' if another entry has the same date, description, and amount (a group of n identical entries means n-1 of them are duplicates). A transaction is an 'anomaly' if its amount differs from the average amount of all entries on the same date (computed before removing duplicates, using all entries on that date) by more than `tolerance` (a Decimal string). Return a sorted list of tuples `(date, description, amount_str)` for entries that are either duplicates or anomalies, where `amount_str` is the amount formatted with exactly 2 decimal places, and the list is sorted by (date, description, amount). Example: entries = [('2024-01-05','Office supplies','45.00'), ('2024-01-05','Office supplies','45.00'), ('2024-01-05','Rent','1200.00'), ('2024-01-05','Coffee','3.50')], tolerance = '500.00' -> the 2024-01-05 average is (45+45+1200+3.50)/4 = 323.375, so Rent (|1200-323.375| > 500) is an anomaly and one copy of Office supplies is a duplicate; the result is [('2024-01-05','Coffee','3.50'), ('2024-01-05','Office supplies','45.00'), ('2024-01-05','Rent','1200.00')] \u2014 note Coffee appears because it also deviates more than 500 from the average (|3.50-323.375| = 319.875... wait, that is less than 500, so Coffee does NOT appear); the correct result is [('2024-01-05','Office supplies','45.00'), ('2024-01-05','Rent','1200.00')]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import Counter\n\ndef find_suspicious(entries, tolerance):\n tol = Decimal(tolerance)\n amounts = [(d, desc, Decimal(a)) for d, desc, a in entries]\n\n # Detect duplicates: entries with same (date, description, amount), all but one flagged\n counts = Counter((d, desc, a) for d, desc, a in amounts)\n remaining = Counter()\n duplicates = set()\n for d, desc, a in amounts:\n key = (d, desc, a)\n remaining[key] += 1\n if remaining[key] > 1:\n duplicates.add((d, desc, a))\n\n # Daily averages over ALL entries on that date (including duplicates)\n daily_totals = {}\n daily_counts = {}\n for d, _, a in amounts:\n daily_totals[d] = daily_totals.get(d, Decimal(0)) + a\n daily_counts[d] = daily_counts.get(d, 0) + 1\n daily_avg = {d: daily_totals[d] / daily_counts[d] for d in daily_totals}\n\n anomalies = set()\n for d, desc, a in amounts:\n if abs(a - daily_avg[d]) > tol:\n anomalies.add((d, desc, a))\n\n flagged = duplicates | anomalies\n result = sorted((d, desc, a.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) for d, desc, a in flagged)\n return [(d, desc, str(a)) for d, desc, a in result]\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-05', 'Office supplies', '45.00'),\n ('2024-01-05', 'Office supplies', '45.00'),\n ('2024-01-05', 'Rent', '1200.00'),\n ('2024-01-05', 'Coffee', '3.50'),\n ]\n print(find_suspicious(entries, '500.00'))\n # Expected: [('2024-01-05', 'Office supplies', '45.00'), ('2024-01-05', 'Rent', '1200.00')]"}], "meta": {"idx": 2315, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 848, "latency_s": 11.0}} +{"prompt": [{"role": "user", "content": "Design an append-only ledger for a small business in which every entry is immutable and chained to the previous entry by a hash, forming a tamper-evident audit trail. Each entry has: an id (sequential, starting at 1), a date string 'YYYY-MM-DD', a description, and a signed Decimal amount (positive = debit, negative = credit). Implement class AuditLedger with methods: add_entry(date, description, amount) -> int (returns new id, amount must be Decimal or int, else raise TypeError), balance() -> Decimal (sum of all amounts, to 2 decimal places), entries_on(date) -> list of entry dicts, and verify() -> bool (True if the hash chain is intact and ids are sequential). Chain rule: entry_hash = sha256 of f'{prev_hash}|{id}|{date}|{description}|{amount}' encoded as UTF-8, with prev_hash of the first entry being 'GENESIS'. Additionally, if any attempt is made to mutate an existing entry (e.g. setting an attribute on a stored entry), verification must still be possible by storing entries as immutable; use a hashable/frozen representation. Example: ledger with entries [('2024-01-01','Opening cash', Decimal('500.00')), ('2024-01-02','Rent', Decimal('-250.00'))] has balance Decimal('250.00'), and verify() returns True; altering the description of entry 2 directly must raise AttributeError (entries are read-only), and verify() must still return True afterwards. Rounding: any amount added must be quantized to 2 decimal places with ROUND_HALF_UP before storing (raise ValueError if more than 2 decimals would be lost, i.e. if quantization changes the value)."}], "completion": [{"role": "assistant", "content": "import hashlib\nfrom decimal import Decimal, ROUND_HALF_UP\n\n\nclass Entry:\n __slots__ = ()\n\n def __init__(self, id, date, description, amount, prev_hash, entry_hash):\n object.__setattr__(self, 'id', id)\n object.__setattr__(self, 'date', date)\n object.__setattr__(self, 'description', description)\n object.__setattr__(self, 'amount', amount)\n object.__setattr__(self, 'prev_hash', prev_hash)\n object.__setattr__(self, 'entry_hash', entry_hash)\n\n def __setattr__(self, name, value):\n raise AttributeError('Entries are immutable')\n\n def __delattr__(self, name):\n raise AttributeError('Entries are immutable')\n\n def as_dict(self):\n return {\n 'id': self.id,\n 'date': self.date,\n 'description': self.description,\n 'amount': self.amount,\n 'prev_hash': self.prev_hash,\n 'entry_hash': self.entry_hash,\n }\n\n def __repr__(self):\n return f'Entry({self.id}, {self.date!r}, {self.description!r}, {self.amount})'\n\n\nclass AuditLedger:\n TWO_PLACES = Decimal('0.01')\n\n @staticmethod\n def _compute_hash(prev_hash, id_, date, description, amount):\n payload = f'{prev_hash}|{id_}|{date}|{description}|{amount}'\n return hashlib.sha256(payload.encode('utf-8')).hexdigest()\n\n def __init__(self):\n self._entries = []\n\n def add_entry(self, date, description, amount):\n if not isinstance(amount, (Decimal, int)) or isinstance(amount, bool):\n raise TypeError('amount must be Decimal or int')\n if isinstance(amount, int):\n amount = Decimal(amount)\n quantized = amount.quantize(self.TWO_PLACES, rounding=ROUND_HALF_UP)\n if quantized != amount:\n raise ValueError('amount has more precision than 2 decimal places')\n id_ = len(self._entries) + 1\n prev_hash = self._entries[-1].entry_hash if self._entries else 'GENESIS'\n entry_hash = self._compute_hash(prev_hash, id_, date, description, quantized)\n entry = Entry(id_, date, description, quantized, prev_hash, entry_hash)\n self._entries.append(entry)\n return id_\n\n def balance(self):\n total = sum((e.amount for e in self._entries), Decimal('0.00'))\n return total.quantize(self.TWO_PLACES, rounding=ROUND_HALF_UP)\n\n def entries_on(self, date):\n return [e.as_dict() for e in self._entries if e.date == date]\n\n def get_entry(self, id_):\n return self._entries[id_ - 1]\n\n def verify(self):\n prev_hash = 'GENESIS'\n for i, e in enumerate(self._entries, start=1):\n if e.id != i:\n return False\n if e.prev_hash != prev_hash:\n return False\n if self._compute_hash(prev_hash, e.id, e.date, e.description, e.amount) != e.entry_hash:\n return False\n prev_hash = e.entry_hash\n return True\n\n\nif __name__ == '__main__':\n from decimal import Decimal as D\n ledger = AuditLedger()\n ledger.add_entry('2024-01-01', 'Opening cash', D('500.00'))\n ledger.add_entry('2024-01-02', 'Rent', D('-250.00'))\n assert ledger.balance() == D('250.00')\n assert ledger.verify() is True\n try:\n ledger.get_entry(2).description = 'Fraud'\n except AttributeError:\n pass\n assert ledger.verify() is True\n print('All checks passed. Balance:', ledger.balance())"}], "meta": {"idx": 2314, "topic": "audit trails and immutable entry logs", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1283, "latency_s": 13.8}} +{"prompt": [{"role": "user", "content": "You are given a general journal (a list of balanced double-entry transactions) and a chart of accounts mapping each account name to exactly one type from: 'asset', 'liability', 'equity', 'revenue', 'expense', 'contra_asset', 'contra_revenue'. Each transaction is a list of (account, debit, credit) lines where debit and credit are Decimal amounts and at most one of them is nonzero per line. Write a function summarize_ledger(journal, chart) that (1) validates every transaction's total debits equal total credits exactly (raising ValueError with the transaction index if not), (2) accumulates net debit balances per account, (3) produces the P&L: gross_revenue = sum of revenue accounts, net_revenue = gross_revenue minus contra_revenue balances, total_expenses = sum of expense accounts, net_income = net_revenue - total_expenses, and (4) produces the balance sheet: total_assets = asset balances minus contra_asset balances, total_liabilities = liability balances, total_equity = equity balances plus net_income (as the closing entry), and it must verify total_assets == total_liabilities + total_equity exactly, raising ArithmeticError if not. All reported figures must be Decimal values quantized to 0.01 with ROUND_HALF_UP. Example: journal = [[('Cash','10000','0'),('Common Stock','0','10000')], [('Equipment','5000','0'),('Cash','0','5000')], [('Depreciation Expense','100','0'),('Accumulated Depreciation','0','100')], [('Accounts Receivable','1200','0'),('Sales Revenue','0','1200')], [('Sales Returns','200','0'),('Accounts Receivable','0','200')], [('Rent Expense','300','0'),('Cash','0','300')]] with chart mapping Cash/Equipment/Accounts Receivable to 'asset', Accumulated Depreciation to 'contra_asset', Common Stock to 'equity', Sales Revenue to 'revenue', Sales Returns to 'contra_revenue', and Depreciation Expense/Rent Expense to 'expense' should return net_income = 600.00, total_assets = 10600.00 (Cash 4700 + AR 1000 + Equipment 5000 - Accum. Dep. 100), total_liabilities = 0.00, and total_equity = 10600.00, and the balance-sheet check must pass since 10600.00 == 0.00 + 10600.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize_ledger(journal, chart):\n \"\"\"Summarize a general journal into P&L and balance-sheet figures.\n\n journal: list of transactions; each transaction is a list of\n (account, debit_str, credit_str) tuples.\n chart: dict mapping account name -> one of 'asset', 'liability',\n 'equity', 'revenue', 'expense', 'contra_asset', 'contra_revenue'.\n\n Returns a dict of Decimals quantized to cents (ROUND_HALF_UP).\n Raises ValueError on an unbalanced transaction,\n ArithmeticError if the balance sheet does not balance.\n \"\"\"\n CENT = Decimal('0.01')\n VALID_TYPES = {'asset', 'liability', 'equity', 'revenue', 'expense',\n 'contra_asset', 'contra_revenue'}\n\n def to_money(value):\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n # --- Validate chart -------------------------------------------------\n for txn in journal:\n for account, _, _ in txn:\n if account not in chart:\n raise ValueError(f\"Account '{account}' missing from chart\")\n if chart[account] not in VALID_TYPES:\n raise ValueError(f\"Invalid account type for '{account}'\")\n\n # --- Validate transactions and accumulate net debit balances --------\n balances = {}\n for idx, txn in enumerate(journal):\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for account, debit, credit in txn:\n d = Decimal(debit)\n c = Decimal(credit)\n if d < 0 or c < 0:\n raise ValueError(f\"Negative amount in transaction {idx}\")\n total_debits += d\n total_credits += c\n balances[account] = balances.get(account, Decimal('0')) + d - c\n if total_debits != total_credits:\n raise ValueError(\n f\"Transaction {idx} is unbalanced: \"\n f\"debits {total_debits} != credits {total_credits}\"\n )\n\n # --- Aggregate by account type --------------------------------------\n sums = {t: Decimal('0') for t in VALID_TYPES}\n for account, balance in balances.items():\n sums[chart[account]] += balance\n\n # --- Income statement ------------------------------------------------\n gross_revenue = sums['revenue']\n net_revenue = gross_revenue - sums['contra_revenue']\n total_expenses = sums['expense']\n net_income = net_revenue - total_expenses\n\n # --- Balance sheet ----------------------------------------------------\n total_assets = sums['asset'] - sums['contra_asset']\n total_liabilities = sums['liability']\n total_equity = sums['equity'] + net_income # closing entry flows NI to equity\n\n q_assets = to_money(total_assets)\n q_liabilities = to_money(total_liabilities)\n q_equity = to_money(total_equity)\n\n if q_assets != q_liabilities + q_equity:\n raise ArithmeticError(\n f\"Balance sheet does not balance: assets {q_assets} != \"\n f\"liabilities {q_liabilities} + equity {q_equity}\"\n )\n\n return {\n 'gross_revenue': to_money(gross_revenue),\n 'net_revenue': to_money(net_revenue),\n 'total_expenses': to_money(total_expenses),\n 'net_income': to_money(net_income),\n 'total_assets': q_assets,\n 'total_liabilities': q_liabilities,\n 'total_equity': q_equity,\n }\n\n\nif __name__ == '__main__':\n journal = [\n [('Cash', '10000', '0'), ('Common Stock', '0', '10000')],\n [('Equipment', '5000', '0'), ('Cash', '0', '5000')],\n [('Depreciation Expense', '100', '0'),\n ('Accumulated Depreciation', '0', '100')],\n [('Accounts Receivable', '1200', '0'), ('Sales Revenue', '0', '1200')],\n [('Sales Returns', '200', '0'), ('Accounts Receivable', '0', '200')],\n [('Rent Expense', '300', '0'), ('Cash', '0', '300')],\n ]\n chart = {\n 'Cash': 'asset',\n 'Equipment': 'asset',\n 'Accounts Receivable': 'asset',\n 'Accumulated Depreciation': 'contra_asset',\n 'Common Stock': 'equity',\n 'Sales Revenue': 'revenue',\n 'Sales Returns': 'contra_revenue',\n 'Depreciation Expense': 'expense',\n 'Rent Expense': 'expense',\n }\n result = summarize_ledger(journal, chart)\n for key, value in result.items():\n print(f\"{key}: {value}\")\n assert result['net_income'] == Decimal('600.00')\n assert result['total_assets'] == Decimal('10600.00')\n assert result['total_liabilities'] == Decimal('0.00')\n assert result['total_equity'] == Decimal('10600.00')\n print('All checks passed.')"}], "meta": {"idx": 2289, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1724, "latency_s": 83.8}} +{"prompt": [{"role": "user", "content": "A trial balance lists every ledger account with its debit or credit balance and is used to check that total debits equal total credits. Write a function `check_trial_balance(accounts)` that takes a list of tuples `(account_name, debit, credit)` where debit and credit are strings representing money (e.g. '1500.00'), and returns a dict with keys 'total_debits', 'total_credits', 'difference', and 'balanced' (a bool). Use `Decimal` for exact arithmetic; amounts may be negative if a balance is flipped, and totals must be rounded to 2 decimal places with ROUND_HALF_UP. For example, input [('Cash','1500.00','0.00'), ('Revenue','0.00','1500.00')] should return {'total_debits': Decimal('1500.00'), 'total_credits': Decimal('1500.00'), 'difference': Decimal('0.00'), 'balanced': True}, while input [('Cash','1500.00','0.00'), ('Revenue','0.00','1499.99')] should return difference Decimal('0.01') and balanced False."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef check_trial_balance(accounts):\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for name, debit, credit in accounts:\n total_debits += Decimal(debit)\n total_credits += Decimal(credit)\n q = Decimal('0.01')\n total_debits = total_debits.quantize(q, rounding=ROUND_HALF_UP)\n total_credits = total_credits.quantize(q, rounding=ROUND_HALF_UP)\n difference = (total_debits - total_credits).quantize(q, rounding=ROUND_HALF_UP)\n return {\n 'total_debits': total_debits,\n 'total_credits': total_credits,\n 'difference': difference,\n 'balanced': difference == 0,\n }\n\nif __name__ == '__main__':\n print(check_trial_balance([('Cash','1500.00','0.00'), ('Revenue','0.00','1500.00')]))\n print(check_trial_balance([('Cash','1500.00','0.00'), ('Revenue','0.00','1499.99')]))"}], "meta": {"idx": 2312, "topic": "trial balance construction and imbalance detection", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 463, "latency_s": 22.7}} +{"prompt": [{"role": "user", "content": "Design a small ledger system using dataclasses and precise monetary handling. Define an `Entry` dataclass with fields `date` (ISO string), `description` (str), `debit` (Decimal, default 0), `credit` (Decimal, default 0), and an `account` (str). Define a `Ledger` class that stores entries and enforces balanced double-entry rules: every posting must be added as a pair of entries (one debit, one credit) with equal amounts, and amounts must be non-negative Decimals rounded to exactly 2 decimal places (raise `ValueError` otherwise). The `Ledger` must provide `balance(account)` returning the net amount (debits minus credits for that account) as a Decimal with 2 decimal places, and `trial_balance()` returning the absolute sum of all account balances, which must equal 0 for a valid ledger. Example: posting a 100.00 debit to 'cash' and a 100.00 credit to 'revenue' on 2024-01-15, then posting 30.50 debit to 'rent-expense' and 30.50 credit to 'cash', should give balance('cash') == Decimal('69.50'), balance('revenue') == Decimal('-100.00'), and trial_balance() == Decimal('0.00')."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\nTWO = Decimal('0.01')\n\n\ndef to_money(value):\n \"\"\"Convert to a Decimal rounded to 2 places; reject negatives.\"\"\"\n if not isinstance(value, Decimal):\n value = Decimal(str(value))\n if value.is_nan() or value.is_infinite():\n raise ValueError(f\"Invalid monetary amount: {value}\")\n if value < 0:\n raise ValueError(f\"Amounts must be non-negative: {value}\")\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\n@dataclass(frozen=True)\nclass Entry:\n date: str\n description: str\n account: str\n debit: Decimal = Decimal('0.00')\n credit: Decimal = Decimal('0.00')\n\n def __post_init__(self):\n object.__setattr__(self, 'debit', to_money(self.debit))\n object.__setattr__(self, 'credit', to_money(self.credit))\n if (self.debit > 0) == (self.credit > 0):\n raise ValueError('An entry must have exactly one of debit or credit > 0')\n\n\nclass Ledger:\n def __init__(self):\n self._entries = []\n self._balances = defaultdict(lambda: Decimal('0.00'))\n\n @property\n def entries(self):\n return list(self._entries)\n\n def post(self, date, description, debit_account, credit_account, amount):\n \"\"\"Post a balanced transaction: debit one account, credit another.\"\"\"\n amt = to_money(amount)\n if amt == 0:\n raise ValueError('Transaction amount must be greater than zero')\n debit_entry = Entry(date=date, description=description,\n account=debit_account, debit=amt)\n credit_entry = Entry(date=date, description=description,\n account=credit_account, credit=amt)\n self._entries.extend([debit_entry, credit_entry])\n self._balances[debit_account] += amt\n self._balances[credit_account] -= amt\n\n def balance(self, account):\n \"\"\"Net balance for an account: total debits minus total credits.\"\"\"\n return self._balances[account].quantize(TWO, rounding=ROUND_HALF_UP)\n\n def trial_balance(self):\n \"\"\"Sum of all account balances (0.00 for a valid ledger).\"\"\"\n total = sum(self._balances.values(), Decimal('0.00'))\n return total.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.post('2024-01-15', 'Client payment', 'cash', 'revenue', Decimal('100.00'))\n ledger.post('2024-02-01', 'Office rent', 'rent-expense', 'cash', Decimal('30.50'))\n assert ledger.balance('cash') == Decimal('69.50')\n assert ledger.balance('revenue') == Decimal('-100.00')\n assert ledger.trial_balance() == Decimal('0.00')\n print('cash:', ledger.balance('cash'))\n print('revenue:', ledger.balance('revenue'))\n print('trial balance:', ledger.trial_balance())\n print('All checks passed.')"}], "meta": {"idx": 2316, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1026, "latency_s": 5.3}} +{"prompt": [{"role": "user", "content": "A restaurant collects tips and pays a 15% booking-commission fee to the platform before splitting the remainder among staff. Write a function `split_tips(gross_tips: str) -> dict` that takes a gross tip amount as a string (e.g. '120.00'), deducts a 15% commission (rounded half-up to the cent, using Decimal with ROUND_HALF_UP), and then splits the net amount equally among 3 staff members: server, cook, and host. The split must be exact: divide the net cents into three equal parts when possible; if the net cents are not divisible by 3, distribute the leftover 1 or 2 cents by giving the extra cent(s) first to the server, then to the cook. Return a dict mapping each role name to a Decimal rounded to 2 places. Example: gross '120.00' -> commission = 18.00, net = 102.00, each gets 34.00, so {'server': Decimal('34.00'), 'cook': Decimal('34.00'), 'host': Decimal('34.00')}. Another example: gross '10.00' -> commission = 1.50, net = 8.50, base share 2.83 each with 1 leftover cent going to the server, so server = 2.84, cook = 2.83, host = 2.83."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef split_tips(gross_tips: str) -> dict:\n gross = Decimal(gross_tips).quantize(CENT, rounding=ROUND_HALF_UP)\n commission = (gross * Decimal('0.15')).quantize(CENT, rounding=ROUND_HALF_UP)\n net_cents = int(((gross - commission) / CENT).quantize(Decimal('1'), rounding=ROUND_HALF_UP))\n base = net_cents // 3\n remainder = net_cents % 3\n shares = {\n 'server': base + (1 if remainder >= 1 else 0),\n 'cook': base + (1 if remainder >= 2 else 0),\n 'host': base,\n }\n return {role: (Decimal(cents) / 100).quantize(CENT) for role, cents in shares.items()}\n\nif __name__ == '__main__':\n print(split_tips('120.00'))\n print(split_tips('10.00'))"}], "meta": {"idx": 2319, "topic": "commission, tip, and percentage splits", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 463, "latency_s": 3.5}} +{"prompt": [{"role": "user", "content": "You are given a bank statement as a list of transactions (each a tuple of date, description, and amount as a string) and a list of amounts recorded in your own ledger. Reconcile the two: for each ledger amount, find and remove one matching bank transaction with the exact same amount (in any order). Then report (1) the total of matched amounts, (2) the total of unmatched bank transactions, and (3) the total of unmatched ledger amounts, all as Decimal values rounded to 2 places. Use Decimal arithmetic to avoid floating-point errors. Example: bank transactions [('2024-01-05', 'Grocery', '-45.10'), ('2024-01-06', 'Rent', '-1200.00'), ('2024-01-07', 'Refund', '50.00')] and ledger amounts ['-45.10', '-1200.00'] should produce matched total Decimal('-1245.10'), unmatched bank total Decimal('50.00'), and unmatched ledger total Decimal('0.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef reconcile(bank_transactions, ledger_amounts):\n \"\"\"Reconcile bank transactions against ledger amounts.\n\n bank_transactions: list of (date, description, amount_str) tuples.\n ledger_amounts: list of amount strings from the ledger.\n\n Returns a dict with matched_total, unmatched_bank_total,\n unmatched_ledger_total as Decimal values rounded to 2 places.\n \"\"\"\n bank = [Decimal(amount) for _, _, amount in bank_transactions]\n ledger = [Decimal(amount) for amount in ledger_amounts]\n\n # Multiset of bank amounts for matching\n remaining_bank = list(bank)\n matched = []\n unmatched_ledger = []\n\n for amount in ledger:\n if amount in remaining_bank:\n remaining_bank.remove(amount)\n matched.append(amount)\n else:\n unmatched_ledger.append(amount)\n\n matched_total = sum(matched, Decimal('0'))\n unmatched_bank_total = sum(remaining_bank, Decimal('0'))\n unmatched_ledger_total = sum(unmatched_ledger, Decimal('0'))\n\n cents = Decimal('0.01')\n return {\n 'matched_total': matched_total.quantize(cents),\n 'unmatched_bank_total': unmatched_bank_total.quantize(cents),\n 'unmatched_ledger_total': unmatched_ledger_total.quantize(cents),\n }\n\n\nif __name__ == '__main__':\n bank = [\n ('2024-01-05', 'Grocery', '-45.10'),\n ('2024-01-06', 'Rent', '-1200.00'),\n ('2024-01-07', 'Refund', '50.00'),\n ]\n ledger = ['-45.10', '-1200.00']\n result = reconcile(bank, ledger)\n print(result)\n assert result['matched_total'] == Decimal('-1245.10')\n assert result['unmatched_bank_total'] == Decimal('50.00')\n assert result['unmatched_ledger_total'] == Decimal('0.00')"}], "meta": {"idx": 2320, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 668, "latency_s": 3.9}} +{"prompt": [{"role": "user", "content": "Implement an inventory cost layer tracker for a small bookstore that supports three valuation methods: FIFO, LIFO, and weighted average (moving average). Purchases append cost layers (quantity, unit cost in cents). Sales remove quantity from layers according to the method: FIFO removes from the oldest layer first, LIFO from the newest, and weighted average replaces all layers with a single layer at the current average unit cost before deducting. All money must be handled with Decimal, rounded with ROUND_HALF_UP to 2 decimal places at each computed unit cost or total. Write a function `inventory_value(layers, sales, method)` where `layers` is a list of (quantity, unit_cost_cents) purchases in chronological order, `sales` is a list of sale quantities in chronological order, and `method` is one of 'FIFO', 'LIFO', or 'AVG'. It must return a tuple (remaining_quantity, inventory_value_cents, cost_of_goods_sold_cents). If a sale exceeds available quantity, raise ValueError. Example: layers=[(100, 300), (50, 350)], sales=[60], method='LIFO' gives: 60 units removed from the newest layer at 350 cents, COGS=60*350=21000 cents, leaving 40 units at 300 cents and 0 at 350, so the result is (90, 12000, 21000). For 'FIFO' the same inputs give (90, 17500, 15500). For 'AVG', the average unit cost is (100*300+50*350)/150 = 316.67 cents (rounded), inventory value 90*316.67 = 28500.30 -> 28500 cents after rounding, COGS 60*316.67 = 19000.20 -> 19000 cents, so the result is (90, 28500, 19000)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round2(x):\n return int(Decimal(x).quantize(Decimal('1'), rounding=ROUND_HALF_UP))\n\n\ndef inventory_value(layers, sales, method):\n if method not in ('FIFO', 'LIFO', 'AVG'):\n raise ValueError('method must be FIFO, LIFO, or AVG')\n\n qty_layers = [[int(q), Decimal(int(c))] for q, c in layers]\n total_qty = sum(q for q, _ in qty_layers)\n\n cogs = Decimal(0)\n\n for sale in sales:\n sale = int(sale)\n if sale < 0:\n raise ValueError('sale quantity must be non-negative')\n if sale > total_qty:\n raise ValueError('sale exceeds available inventory')\n\n if method == 'AVG':\n if total_qty > 0:\n avg_cost = (sum(q * c for q, c in qty_layers) / Decimal(total_qty))\n avg_cost = avg_cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n qty_layers = [[total_qty, avg_cost]]\n remaining = sale\n while remaining > 0:\n q, c = qty_layers[0]\n take = min(q, remaining)\n cogs += Decimal(take) * c\n q -= take\n remaining -= take\n if q == 0:\n qty_layers.pop(0)\n else:\n qty_layers[0] = [q, c]\n break\n total_qty -= sale\n else:\n remaining = sale\n while remaining > 0:\n idx = 0 if method == 'FIFO' else len(qty_layers) - 1\n q, c = qty_layers[idx]\n take = min(q, remaining)\n cogs += Decimal(take) * c\n q -= take\n remaining -= take\n if q == 0:\n qty_layers.pop(idx)\n else:\n qty_layers[idx] = [q, c]\n total_qty -= sale\n\n value = sum(Decimal(q) * c for q, c in qty_layers)\n return (total_qty, _round2(value), _round2(cogs))\n\n\nif __name__ == '__main__':\n layers = [(100, 300), (50, 350)]\n assert inventory_value(layers, [60], 'LIFO') == (90, 12000, 21000)\n assert inventory_value(layers, [60], 'FIFO') == (90, 17500, 15500)\n assert inventory_value(layers, [60], 'AVG') == (90, 28500, 19000)\n assert inventory_value([(10, 100)], [15], 'FIFO') if False else True\n try:\n inventory_value([(10, 100)], [15], 'FIFO')\n assert False, 'expected ValueError'\n except ValueError:\n pass\n print('All tests passed.')"}], "meta": {"idx": 2322, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1020, "latency_s": 9.8}} +{"prompt": [{"role": "user", "content": "A company keeps its books on a cash basis but must produce an accrual-basis income statement for the period. You are given a list of cash transactions during a month and two lists of balance adjustments at month end: accounts receivable (revenue earned but not yet collected) and accounts payable (expenses incurred but not yet paid). Each cash transaction is a tuple (date, kind, amount) where kind is either 'cash_in' (customer payment) or 'cash_out' (payment for expenses), and amount is a non-negative string in dollars and cents. Write a function accrual_report(transactions, receivables, payables) that returns a dict with keys 'accrual_revenue', 'accrual_expenses', and 'net_income', each a Decimal rounded to exactly 2 decimal places using ROUND_HALF_UP. Accrual revenue equals total cash received from customers PLUS the increase in receivables (i.e., amounts in the receivables list); accrual expenses equals total cash paid for expenses PLUS the increase in payables; net income is accrual revenue minus accrual expenses. All arithmetic must use Decimal, never float. For example, accrual_report([('2024-05-02','cash_in','1500.00'), ('2024-05-10','cash_out','800.50'), ('2024-05-15','cash_in','250.75')], ['1200.00'], ['450.25']) should return {'accrual_revenue': Decimal('2950.75'), 'accrual_expenses': Decimal('1250.75'), 'net_income': Decimal('1700.00')}. Ignore any transaction whose kind is neither 'cash_in' nor 'cash_out'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef accrual_report(transactions, receivables, payables):\n \"\"\"Convert cash-basis transactions plus accrual adjustments into an\n accrual-basis income summary.\n\n Args:\n transactions: iterable of (date, kind, amount) tuples, amount as str.\n receivables: iterable of amount strings earned but not collected.\n payables: iterable of amount strings incurred but not paid.\n\n Returns:\n dict with 'accrual_revenue', 'accrual_expenses', 'net_income' as\n Decimal values quantized to 2 places with ROUND_HALF_UP.\n \"\"\"\n cash_in = Decimal('0')\n cash_out = Decimal('0')\n\n for record in transactions:\n date, kind, amount = record[0], record[1], record[2]\n value = Decimal(str(amount))\n if kind == 'cash_in':\n cash_in += value\n elif kind == 'cash_out':\n cash_out += value\n # Any other kind is ignored per the specification.\n\n receivable_increase = sum((Decimal(str(a)) for a in receivables), Decimal('0'))\n payable_increase = sum((Decimal(str(a)) for a in payables), Decimal('0'))\n\n two_places = Decimal('0.01')\n\n accrual_revenue = (cash_in + receivable_increase).quantize(two_places, rounding=ROUND_HALF_UP)\n accrual_expenses = (cash_out + payable_increase).quantize(two_places, rounding=ROUND_HALF_UP)\n net_income = (accrual_revenue - accrual_expenses).quantize(two_places, rounding=ROUND_HALF_UP)\n\n return {\n 'accrual_revenue': accrual_revenue,\n 'accrual_expenses': accrual_expenses,\n 'net_income': net_income,\n }\n\n\nif __name__ == '__main__':\n result = accrual_report(\n [('2024-05-02', 'cash_in', '1500.00'),\n ('2024-05-10', 'cash_out', '800.50'),\n ('2024-05-15', 'cash_in', '250.75')],\n ['1200.00'],\n ['450.25'],\n )\n print(result)\n assert result == {\n 'accrual_revenue': Decimal('2950.75'),\n 'accrual_expenses': Decimal('1250.75'),\n 'net_income': Decimal('1700.00'),\n }"}], "meta": {"idx": 2323, "topic": "accrual versus cash basis adjustments", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 893, "latency_s": 10.2}} +{"prompt": [{"role": "user", "content": "Write a function `variance_report(budget: dict, actual: dict, tolerance: str) -> list` that compares budgeted amounts against actual amounts per account and produces a variance report. Each dict maps account names to monetary amounts given as strings (e.g. \"1200.50\"). For each account present in either dict, compute variance = actual - budget using Decimal arithmetic with ROUND_HALF_UP quantization to cents. Classify each variance as 'OVER' if it exceeds the tolerance, 'UNDER' if it is less than the negative of tolerance, and 'OK' otherwise (tolerance is a string like \"50.00\"). The report is a list of tuples (account, variance_string, classification), sorted by account name, where variance_string is the variance formatted to two decimal places (negative variances shown like \"-75.25\"). Accounts missing from a dict are treated as amount 0.00. Example: budget = {\"Office Supplies\": \"500.00\", \"Rent\": \"2000.00\"}, actual = {\"Office Supplies\": \"620.50\", \"Rent\": \"2000.00\", \"Marketing\": \"75.25\"}, tolerance = \"100.00\" yields [('Marketing', '-75.25', 'OK'), ('Office Supplies', '120.50', 'OVER'), ('Rent', '0.00', 'OK')]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef variance_report(budget: dict, actual: dict, tolerance: str) -> list:\n cent = Decimal(\"0.01\")\n tol = Decimal(tolerance).quantize(cent, rounding=ROUND_HALF_UP)\n\n def to_amount(value):\n return Decimal(value).quantize(cent, rounding=ROUND_HALF_UP)\n\n accounts = sorted(set(budget) | set(actual))\n report = []\n for account in accounts:\n budgeted = to_amount(budget.get(account, \"0.00\"))\n spent = to_amount(actual.get(account, \"0.00\"))\n variance = (spent - budgeted).quantize(cent, rounding=ROUND_HALF_UP)\n if variance > tol:\n classification = \"OVER\"\n elif variance < -tol:\n classification = \"UNDER\"\n else:\n classification = \"OK\"\n report.append((account, str(variance), classification))\n return report\n\n\nif __name__ == \"__main__\":\n budget = {\"Office Supplies\": \"500.00\", \"Rent\": \"2000.00\"}\n actual = {\"Office Supplies\": \"620.50\", \"Rent\": \"2000.00\", \"Marketing\": \"75.25\"}\n result = variance_report(budget, actual, \"100.00\")\n expected = [('Marketing', '-75.25', 'OK'), ('Office Supplies', '120.50', 'OVER'), ('Rent', '0.00', 'OK')]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2324, "topic": "budget versus actual variance analysis", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 627, "latency_s": 6.4}} +{"prompt": [{"role": "user", "content": "Build an invoice-to-ledger engine for mixed-rate VAT invoices using Python's Decimal arithmetic. Input is a list of lines, each a pair of decimal strings (net_amount, vat_rate) such as ('100.00', '0.25'), where rates may be 0 and net amounts may be negative (credit-note lines). Compute: (1) the exact net total; (2) VAT payable per rate, where the unrounded VAT (net * rate) of all lines sharing a rate is summed and rounded once per rate to cents using ROUND_HALF_UP (ties away from zero); (3) gross = net total + all VAT payable; (4) the cash-rounded amount due, obtained by rounding gross to the nearest 0.05 (ties away from zero); and (5) a double-entry ledger that must balance exactly: debit Accounts Receivable with the amount due, credit Sales Revenue with the net total, credit one 'VAT Payable (rate)' account per rate group, and post the cash-rounding difference (amount due minus gross) to Rounding Income (credit) if positive or Rounding Expense (debit) if negative. Additionally report the discrepancy between each rate's invoice-level VAT and the sum of that rate's per-line VAT rounded to cents individually. Worked example: lines [('100.00','0.25'), ('49.99','0.12'), ('10.00','0.06'), ('25.50','0'), ('0.01','0.25'), ('0.01','0.25'), ('0.01','0.25')] give net_total 185.52; VAT payable 25%: 25.01 (25.0075 rounded up), 12%: 6.00 (5.9988 rounded up), 6%: 0.60, 0%: 0.00; per-line VAT discrepancy at 25% is 0.01 (three lines of 0.0025 each round to 0.00 individually); gross 217.13; amount_due 217.15 (rounded to nearest 0.05); ledger: Dr Accounts Receivable 217.15, Cr Sales Revenue 185.52, Cr VAT Payable (0.25) 25.01, Cr VAT Payable (0.12) 6.00, Cr VAT Payable (0.06) 0.60, Cr VAT Payable (0) 0.00, Cr Rounding Income 0.02 \u2014 total debits equal total credits at 217.15."}], "completion": [{"role": "assistant", "content": "import json\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nNICKEL = Decimal(\"0.05\")\nZERO = Decimal(\"0.00\")\n\n\ndef round_cent(amount):\n \"\"\"Round to cents, ties away from zero (ROUND_HALF_UP in decimal).\"\"\"\n return amount.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef round_nickel(amount):\n \"\"\"Round to the nearest 0.05, ties away from zero.\"\"\"\n units = (amount / NICKEL).quantize(Decimal(\"1\"), rounding=ROUND_HALF_UP)\n return units * NICKEL\n\n\ndef compute_invoice(lines):\n \"\"\"Process invoice lines and produce totals, VAT breakdown, and a balanced ledger.\n\n lines: iterable of (net_amount, vat_rate) pairs of decimal strings.\n Returns a dict of results; raises AssertionError if the ledger does not balance.\n \"\"\"\n net_total = Decimal(\"0\")\n net_by_rate = {}\n vat_exact_by_rate = {} # unrounded VAT accumulated per rate\n vat_line_rounded_by_rate = {} # per-line rounded VAT accumulated per rate\n\n for net_s, rate_s in lines:\n net = Decimal(net_s)\n rate = Decimal(rate_s)\n key = str(rate)\n net_total += net\n net_by_rate[key] = net_by_rate.get(key, Decimal(\"0\")) + net\n exact_vat = net * rate\n vat_exact_by_rate[key] = vat_exact_by_rate.get(key, Decimal(\"0\")) + exact_vat\n vat_line_rounded_by_rate[key] = (\n vat_line_rounded_by_rate.get(key, Decimal(\"0\")) + round_cent(exact_vat)\n )\n\n # Invoice-level VAT: round once per rate group.\n vat_by_rate = {k: round_cent(v) for k, v in vat_exact_by_rate.items()}\n vat_total = sum(vat_by_rate.values(), Decimal(\"0\"))\n\n # Discrepancy between invoice-level VAT and sum of per-line rounded VAT.\n line_rounding_discrepancy = {\n k: vat_by_rate[k] - vat_line_rounded_by_rate[k] for k in vat_by_rate\n }\n\n gross = net_total + vat_total\n amount_due = round_nickel(gross)\n cash_rounding_diff = amount_due - gross\n\n # Build the double-entry ledger.\n ledger = [\n {\"account\": \"Accounts Receivable\", \"debit\": round_cent(amount_due), \"credit\": ZERO}\n ]\n if net_total != 0:\n ledger.append({\"account\": \"Sales Revenue\", \"debit\": ZERO, \"credit\": net_total})\n\n # One VAT payable account per rate, ordered by descending rate.\n for key in sorted(vat_by_rate, key=Decimal, reverse=True):\n amt = vat_by_rate[key]\n if amt != 0 or Decimal(key) == 0:\n ledger.append(\n {\"account\": \"VAT Payable (\" + key + \")\", \"debit\": ZERO, \"credit\": amt}\n )\n\n if cash_rounding_diff > 0:\n ledger.append(\n {\"account\": \"Rounding Income\", \"debit\": ZERO, \"credit\": cash_rounding_diff}\n )\n elif cash_rounding_diff < 0:\n ledger.append(\n {\"account\": \"Rounding Expense\", \"debit\": -cash_rounding_diff, \"credit\": ZERO}\n )\n\n # Verify the ledger balances exactly.\n total_debits = sum((e[\"debit\"] for e in ledger), Decimal(\"0\"))\n total_credits = sum((e[\"credit\"] for e in ledger), Decimal(\"0\"))\n assert total_debits == total_credits, \"ledger out of balance\"\n assert total_debits == round_cent(amount_due), \"ledger does not match amount due\"\n\n return {\n \"net_total\": net_total,\n \"vat_by_rate\": vat_by_rate,\n \"vat_total\": vat_total,\n \"line_rounding_discrepancy\": line_rounding_discrepancy,\n \"gross\": gross,\n \"amount_due\": amount_due,\n \"cash_rounding_diff\": cash_rounding_diff,\n \"ledger\": ledger,\n \"total_debits\": total_debits,\n \"total_credits\": total_credits,\n }\n\n\ndef main():\n example_lines = [\n (\"100.00\", \"0.25\"),\n (\"49.99\", \"0.12\"),\n (\"10.00\", \"0.06\"),\n (\"25.50\", \"0\"),\n (\"0.01\", \"0.25\"),\n (\"0.01\", \"0.25\"),\n (\"0.01\", \"0.25\"),\n ]\n result = compute_invoice(example_lines)\n\n # Check the worked example.\n assert result[\"net_total\"] == Decimal(\"185.52\")\n assert result[\"vat_by_rate\"][\"0.25\"] == Decimal(\"25.01\")\n assert result[\"vat_by_rate\"][\"0.12\"] == Decimal(\"6.00\")\n assert result[\"vat_by_rate\"][\"0.06\"] == Decimal(\"0.60\")\n assert result[\"vat_by_rate\"][\"0\"] == Decimal(\"0.00\")\n assert result[\"line_rounding_discrepancy\"][\"0.25\"] == Decimal(\"0.01\")\n assert result[\"gross\"] == Decimal(\"217.13\")\n assert result[\"amount_due\"] == Decimal(\"217.15\")\n assert result[\"cash_rounding_diff\"] == Decimal(\"0.02\")\n assert result[\"total_debits\"] == result[\"total_credits\"] == Decimal(\"217.15\")\n\n # A credit-note style invoice with negative lines must also balance.\n credit_result = compute_invoice([( \"-13.37\", \"0.25\"), (\"-2.01\", \"0.12\")])\n assert credit_result[\"total_debits\"] == credit_result[\"total_credits\"]\n\n # Serialize for the report (Decimals as fixed-point strings).\n def encode(obj):\n if isinstance(obj, Decimal):\n return str(obj.quantize(CENT, rounding=ROUND_HALF_UP))\n if isinstance(obj, dict):\n return {k: encode(v) for k, v in obj.items()}\n if isinstance(obj, list):\n return [encode(v) for v in obj]\n return obj\n\n print(json.dumps(encode(result), indent=2))\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2307, "topic": "sales tax and VAT computation and rounding", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1830, "latency_s": 52.4}} +{"prompt": [{"role": "user", "content": "Implement an FX revaluation engine for a company whose base currency is USD, processing a chronological list of transactions of three kinds: BUY (purchase foreign currency units at a quoted USD rate), SELL (dispose of foreign currency units back into USD at a quoted rate), and PAY (use held inventory of a foreign currency to settle a payable that was originally recorded in the books at a given USD amount). Track, per currency, the units held and their USD book value using the weighted-average cost method, so the cost basis of any disposal is (units disposed) x (current book value / current units held). Realized FX gain/loss is proceeds_in_USD minus cost basis for a SELL, and recorded_usd minus cost basis for a PAY; each transaction's realized gain must be rounded to cents with ROUND_HALF_UP and accumulated, and a SELL or PAY exceeding the inventory must raise ValueError. At period end, revalue each remaining position at its closing rate: market value = units x closing rate and unrealized gain = market value - book value, with all USD amounts in the report rounded to cents and units rounded to the currency's minor unit (0 decimals for JPY, 2 otherwise). The engine must return a report containing, per open currency: units, book value, closing rate, market value, unrealized gain; plus totals for realized gain, unrealized gain, and overall FX gain/loss. Worked example: BUY 10000 EUR @ 1.10 and BUY 5000 EUR @ 1.15 give 15000 EUR at book 16750.00 USD; SELL 6000 EUR @ 1.20 has basis 6700.00 and proceeds 7200.00, so realized gain is 500.00; PAY 3000 EUR recorded at 3350.00 USD has basis 3350.00, so gain is 0.00; the remaining 6000 EUR at book 6700.00 revalued at a closing rate of 1.18 has market value 7080.00 and unrealized gain 380.00, giving totals of realized 500.00, unrealized 380.00, and total FX gain 880.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\nCENT = Decimal(\"0.01\")\nUNIT = Decimal(\"1\")\nZERO = Decimal(\"0\")\n\n\ndef q2(value):\n \"\"\"Round a USD monetary amount to cents, half-up.\"\"\"\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\nclass FXLedger:\n \"\"\"Multi-currency ledger with weighted-average cost and FX revaluation.\"\"\"\n\n def __init__(self, base_currency=\"USD\"):\n self.base_currency = base_currency\n self.units = defaultdict(Decimal) # Decimal() == 0\n self.book_value = defaultdict(Decimal) # USD book value per currency\n self.realized_by_currency = defaultdict(Decimal)\n self.realized_total = ZERO\n\n def _quantize_units(self, currency, amount):\n \"\"\"Round units to the currency's minor unit (JPY: 0 dp, others: 2 dp).\"\"\"\n step = UNIT if currency == \"JPY\" else CENT\n return amount.quantize(step, rounding=ROUND_HALF_UP)\n\n def _cost_basis(self, currency, amount):\n held = self.units[currency]\n if held == 0:\n raise ValueError(f\"no inventory of {currency} held\")\n return amount * self.book_value[currency] / held\n\n def apply(self, txn):\n ttype = txn[\"type\"].upper()\n currency = txn[\"currency\"]\n amount = self._quantize_units(currency, Decimal(str(txn[\"amount\"])))\n\n if ttype == \"BUY\":\n rate = Decimal(str(txn[\"rate\"]))\n cost = q2(amount * rate)\n self.units[currency] += amount\n self.book_value[currency] += cost\n\n elif ttype == \"SELL\":\n if amount > self.units[currency]:\n raise ValueError(\n f\"insufficient {currency} inventory: need {amount}, \"\n f\"held {self.units[currency]}\"\n )\n basis = self._cost_basis(currency, amount)\n proceeds = q2(amount * Decimal(str(txn[\"rate\"])))\n gain = q2(proceeds - basis)\n self.realized_by_currency[currency] += gain\n self.realized_total += gain\n self.units[currency] -= amount\n self.book_value[currency] -= basis\n\n elif ttype == \"PAY\":\n if amount > self.units[currency]:\n raise ValueError(\n f\"insufficient {currency} inventory: need {amount}, \"\n f\"held {self.units[currency]}\"\n )\n basis = self._cost_basis(currency, amount)\n recorded = q2(Decimal(str(txn[\"recorded_usd\"])))\n gain = q2(recorded - basis)\n self.realized_by_currency[currency] += gain\n self.realized_total += gain\n self.units[currency] -= amount\n self.book_value[currency] -= basis\n\n else:\n raise ValueError(f\"unknown transaction type: {ttype}\")\n\n def closing_report(self, closing_rates):\n \"\"\"Revalue open positions and build the FX gain/loss report.\"\"\"\n accounts = {}\n unrealized_total = ZERO\n\n for currency in sorted(self.units):\n units = self.units[currency]\n book = q2(self.book_value[currency])\n if units == 0 and book == 0:\n continue # fully closed position, nothing to revalue\n if currency not in closing_rates:\n raise ValueError(f\"missing closing rate for {currency}\")\n rate = Decimal(str(closing_rates[currency]))\n market = q2(units * rate)\n unrealized = q2(market - book)\n accounts[currency] = {\n \"units\": str(self._quantize_units(currency, units)),\n \"book_value_usd\": str(book),\n \"closing_rate\": str(rate),\n \"market_value_usd\": str(market),\n \"unrealized_gain_usd\": str(unrealized),\n }\n unrealized_total += unrealized\n\n return {\n \"base_currency\": self.base_currency,\n \"accounts\": accounts,\n \"realized_gain_usd\": str(q2(self.realized_total)),\n \"realized_gain_by_currency_usd\": {\n cur: str(q2(gain))\n for cur, gain in sorted(self.realized_by_currency.items())\n },\n \"unrealized_gain_usd\": str(q2(unrealized_total)),\n \"total_fx_gain_usd\": str(q2(self.realized_total + unrealized_total)),\n }\n\n\ndef run_fx_engine(transactions, closing_rates, base_currency=\"USD\"):\n \"\"\"Convenience entry point: apply all transactions, then revalue.\"\"\"\n ledger = FXLedger(base_currency)\n for txn in transactions:\n ledger.apply(txn)\n return ledger.closing_report(closing_rates)\n\n\nif __name__ == \"__main__\":\n transactions = [\n {\"type\": \"BUY\", \"currency\": \"EUR\", \"amount\": \"10000\", \"rate\": \"1.10\"},\n {\"type\": \"BUY\", \"currency\": \"EUR\", \"amount\": \"5000\", \"rate\": \"1.15\"},\n {\"type\": \"SELL\", \"currency\": \"EUR\", \"amount\": \"6000\", \"rate\": \"1.20\"},\n {\"type\": \"PAY\", \"currency\": \"EUR\", \"amount\": \"3000\", \"recorded_usd\": \"3350.00\"},\n ]\n report = run_fx_engine(transactions, {\"EUR\": \"1.18\"})\n\n eur = report[\"accounts\"][\"EUR\"]\n assert eur[\"units\"] == \"6000\"\n assert eur[\"book_value_usd\"] == \"6700.00\"\n assert eur[\"market_value_usd\"] == \"7080.00\"\n assert eur[\"unrealized_gain_usd\"] == \"380.00\"\n assert report[\"realized_gain_usd\"] == \"500.00\"\n assert report[\"unrealized_gain_usd\"] == \"380.00\"\n assert report[\"total_fx_gain_usd\"] == \"880.00\"\n\n # Over-selling must fail.\n try:\n FXLedger().apply({\"type\": \"SELL\", \"currency\": \"EUR\", \"amount\": \"1\", \"rate\": \"1.0\"})\n raise AssertionError(\"expected ValueError for empty inventory\")\n except ValueError:\n pass\n\n print(report)"}], "meta": {"idx": 2310, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1984, "latency_s": 47.9}} +{"prompt": [{"role": "user", "content": "Write a function `amortization_schedule(principal, annual_rate, years, extra_payment=0)` that builds a monthly loan amortization ledger using Decimal arithmetic with ROUND_HALF_UP rounding to cents. The monthly payment is computed as `p = principal * i / (1 - (1+i)**-n)` where `i` is the monthly rate (annual_rate/12) and `n` is years*12, rounded to cents; on the final payment, pay only the remaining balance plus interest so the loan is not overpaid. Each monthly ledger entry records period, payment, interest (balance*i rounded to cents), principal reduction (payment minus interest, or the remaining balance on the last entry), and ending balance. Extra payment (a Decimal, default 0) is added to the payment each month and applied entirely to principal. Return a list of tuples `(period, payment, interest, principal, balance)` and raise ValueError if principal <= 0, annual_rate < 0, years <= 0, or extra_payment < 0. Example: principal=1000, annual_rate=0.12, years=1, extra_payment=0 gives monthly payment Decimal('88.85'); the first entry is (1, Decimal('88.85'), Decimal('10.00'), Decimal('78.85'), Decimal('921.15')) and the final entry has balance Decimal('0.00') after 12 periods (extra payments shorten the schedule)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, getcontext\n\ngetcontext().rounding = ROUND_HALF_UP\nCENT = Decimal('0.01')\n\n\ndef _round(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef amortization_schedule(principal, annual_rate, years, extra_payment=Decimal('0')):\n principal = Decimal(str(principal))\n annual_rate = Decimal(str(annual_rate))\n years = int(years)\n extra_payment = Decimal(str(extra_payment))\n\n if principal <= 0:\n raise ValueError('principal must be positive')\n if annual_rate < 0:\n raise ValueError('annual_rate must be non-negative')\n if years <= 0:\n raise ValueError('years must be positive')\n if extra_payment < 0:\n raise ValueError('extra_payment must be non-negative')\n\n i = annual_rate / Decimal(12)\n n = years * 12\n if i == 0:\n base_payment = principal / n\n else:\n base_payment = principal * i / (Decimal(1) - (Decimal(1) + i) ** (-n))\n payment = _round(base_payment) + extra_payment\n\n schedule = []\n balance = principal\n period = 0\n while balance > 0:\n period += 1\n interest = _round(balance * i)\n if payment >= balance + interest:\n this_payment = balance + interest\n this_principal = balance\n else:\n this_payment = payment\n this_principal = payment - interest\n balance = balance - this_principal\n schedule.append((period, _round(this_payment), interest, _round(this_principal), _round(balance)))\n return schedule\n\n\nif __name__ == '__main__':\n for row in amortization_schedule(1000, Decimal('0.12'), 1):\n print(row)"}], "meta": {"idx": 2318, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 739, "latency_s": 28.4}} +{"prompt": [{"role": "user", "content": "At period end, a bookkeeper must post closing entries that zero out the temporary (nominal) accounts and transfer their net balances to Retained Earnings, then produce a post-closing trial balance. You are given a general ledger as a dict mapping account names to their pre-closing balances in cents (integers, where positive means debit balance and negative means credit balance). Revenue accounts are those whose names start with 'Revenue', and expense accounts start with 'Expense'. Write a function close_period(ledger) that returns a tuple (closing_entries, post_closing_balance_total) where closing_entries is a list of strings formatted as 'DEBIT ' or 'CREDIT ' describing the closing entries, and post_closing_balance_total is the sum of all account balances after closing (which must equal the sum of the permanent account balances). Each revenue account is debited by its balance to zero it; each expense account is credited by its balance to zero it; the net difference is credited to (or debited from) 'Retained Earnings' as needed. If Retained Earnings does not exist in the ledger, treat it as starting at 0 and include it in the output entries/total only if a closing entry touches it. For example, ledger = {'Revenue-Sales': -50000, 'Expense-Rent': 20000, 'Expense-Salaries': 30000, 'Cash': 10000, 'Capital': -30000} yields closing entries debiting Revenue-Sales for 50000, crediting Expense-Rent for 20000, crediting Expense-Salaries for 30000 (net income of 0, so no Retained Earnings entry), and a post-closing balance total of -20000 (Cash 10000 + Capital -30000). Entries for revenues and expenses must be listed in the original dict insertion order."}], "completion": [{"role": "assistant", "content": "def close_period(ledger):\n closing_entries = []\n net = 0 # positive means net income (credit to Retained Earnings)\n for account, balance in ledger.items():\n if account.startswith('Revenue'):\n if balance != 0:\n # Debit revenue to zero out a credit balance (negative)\n amount = -balance\n closing_entries.append('DEBIT {} {}'.format(account, amount))\n ledger[account] = 0\n net += amount\n elif account.startswith('Expense'):\n if balance != 0:\n # Credit expense to zero out a debit balance (positive)\n amount = balance\n closing_entries.append('CREDIT {} {}'.format(account, amount))\n ledger[account] = 0\n net -= amount\n if net != 0:\n if 'Retained Earnings' in ledger:\n ledger['Retained Earnings'] += net\n else:\n ledger['Retained Earnings'] = net\n if net > 0:\n closing_entries.append('CREDIT Retained Earnings {}'.format(net))\n else:\n closing_entries.append('DEBIT Retained Earnings {}'.format(-net))\n total = sum(ledger.values())\n return (closing_entries, total)\n\n\nif __name__ == '__main__':\n ledger = {'Revenue-Sales': -50000, 'Expense-Rent': 20000,\n 'Expense-Salaries': 30000, 'Cash': 10000, 'Capital': -30000}\n entries, total = close_period(ledger)\n assert entries == ['DEBIT Revenue-Sales 50000', 'CREDIT Expense-Rent 20000',\n 'CREDIT Expense-Salaries 30000']\n assert total == -20000\n\n ledger2 = {'Revenue-Sales': -80000, 'Expense-Rent': 20000, 'Cash': 5000}\n entries2, total2 = close_period(ledger2)\n assert entries2 == ['DEBIT Revenue-Sales 80000', 'CREDIT Expense-Rent 20000',\n 'CREDIT Retained Earnings 60000']\n assert total2 == 5000\n assert ledger2['Retained Earnings'] == -60000\n\n ledger3 = {'Revenue-Fees': -10000, 'Expense-Loss': 30000, 'Capital': -20000}\n entries3, total3 = close_period(ledger3)\n assert entries3 == ['DEBIT Revenue-Fees 10000', 'CREDIT Expense-Loss 30000',\n 'DEBIT Retained Earnings 20000']\n assert total3 == -20000\n print('All tests passed.')"}], "meta": {"idx": 2328, "topic": "period-end closing entries and routines", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1019, "latency_s": 9.6}} +{"prompt": [{"role": "user", "content": "You are reconciling a small agency's commission ledger. Each sale record is a line of the form 'id,amount,agent' where amount is a decimal string. The agency keeps a 20% commission rounded to the nearest cent with ROUND_HALF_UP; the remaining 80% is split equally among the sale's assigned agents (one or more names, comma-separated after the amount). Write a program that reads sales from stdin (one per line, possibly with blank lines to ignore) and prints a payout report: for each agent (sorted alphabetically) a line 'agent: $X.XX' showing the sum of their per-sale payout shares, where each individual share is computed on the sale's net (80% of amount) divided by the number of agents and rounded to the nearest cent with ROUND_HALF_UP, and finally a line 'total_commission: $Y.YY' for the sum of per-sale commissions. Use Decimal for all arithmetic. Example: input 'S1,100.00,Alice,Bob' gives commission $20.00 and net $80.00, so each agent gets $40.00; a second line 'S2,50.55,Carol' gives commission $10.11 (50.55*0.20 = 10.11) and Carol $32.44 (50.55*0.80 = 40.44). The report is: 'Alice: $40.00', 'Bob: $40.00', 'Carol: $32.44', 'total_commission: $30.11'."}], "completion": [{"role": "assistant", "content": "import sys\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef round_cent(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef main():\n payouts = {}\n total_commission = Decimal('0.00')\n for line in sys.stdin:\n line = line.strip()\n if not line:\n continue\n parts = [p.strip() for p in line.split(',')]\n sale_id, amount_str = parts[0], parts[1]\n agents = parts[2:]\n amount = Decimal(amount_str)\n commission = round_cent(amount * Decimal('0.20'))\n net = amount - commission\n share = round_cent(net / Decimal(len(agents)))\n total_commission += commission\n for agent in agents:\n payouts[agent] = payouts.get(agent, Decimal('0.00')) + share\n for agent in sorted(payouts):\n print(f\"{agent}: ${round_cent(payouts[agent])}\")\n print(f\"total_commission: ${round_cent(total_commission)}\")\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2321, "topic": "commission, tip, and percentage splits", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 553, "latency_s": 29.6}} +{"prompt": [{"role": "user", "content": "Write a function `compute_net_pay(gross_pay, federal_rate, state_rate, pretax_deductions)` that calculates an employee's net pay for one pay period. Federal and state withholding tax rates are given as percentages (e.g., 12.5 means 12.5%). Pretax deductions (such as health insurance or 401k) are subtracted from gross pay before taxes are computed. The taxable wages equal gross_pay minus pretax_deductions; federal tax is federal_rate% of taxable wages, state tax is state_rate% of taxable wages, and net pay is taxable wages minus both taxes. All money amounts must be handled with the Decimal type and rounded to the nearest cent (ROUND_HALF_UP) at each intermediate step. The function returns a dictionary with keys 'taxable_wages', 'federal_tax', 'state_tax', and 'net_pay', each a Decimal rounded to 2 decimal places. For example, compute_net_pay(Decimal('2500.00'), 15.0, 5.0, Decimal('300.00')) should return {'taxable_wages': Decimal('2200.00'), 'federal_tax': Decimal('330.00'), 'state_tax': Decimal('110.00'), 'net_pay': Decimal('1760.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef compute_net_pay(gross_pay, federal_rate, state_rate, pretax_deductions):\n \"\"\"Compute net pay with federal/state withholdings and pretax deductions.\"\"\"\n CENT = Decimal('0.01')\n\n def to_cent(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n gross_pay = to_cent(Decimal(str(gross_pay)))\n pretax_deductions = to_cent(Decimal(str(pretax_deductions)))\n\n taxable_wages = to_cent(gross_pay - pretax_deductions)\n federal_tax = to_cent(taxable_wages * Decimal(str(federal_rate)) / Decimal('100'))\n state_tax = to_cent(taxable_wages * Decimal(str(state_rate)) / Decimal('100'))\n net_pay = to_cent(taxable_wages - federal_tax - state_tax)\n\n return {\n 'taxable_wages': taxable_wages,\n 'federal_tax': federal_tax,\n 'state_tax': state_tax,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = compute_net_pay(Decimal('2500.00'), 15.0, 5.0, Decimal('300.00'))\n print(result)\n assert result == {\n 'taxable_wages': Decimal('2200.00'),\n 'federal_tax': Decimal('330.00'),\n 'state_tax': Decimal('110.00'),\n 'net_pay': Decimal('1760.00'),\n }"}], "meta": {"idx": 2329, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 582, "latency_s": 5.3}} +{"prompt": [{"role": "user", "content": "You are given a list of unposted journal entries, each represented as a dict with keys 'date', 'memo', and 'lines', where 'lines' is a list of (account, debit, credit) tuples with Decimal amounts. Write a function `post_entries(entries, opening_balances)` that (1) validates each entry: total debits must equal total credits (raise ValueError with a message containing 'unbalanced' if not), and no line may have both a nonzero debit and a nonzero credit (raise ValueError containing 'invalid line' if violated); (2) posts each entry to a general ledger, computing running balances for each account, where debit-normal accounts (names starting with 'asset:' or 'expense:') increase with debits, and all other accounts (liability, equity, revenue) increase with credits; (3) returns a dict mapping each account to its final balance as a Decimal (positive means the normal-side balance). Amounts should be quantized to 0.01 with ROUND_HALF_UP when stored. Example: entries = [{'date':'2024-01-01','memo':'sale','lines':[('asset:cash', '100.00', '0'), ('revenue:sales', '0', '100.00')]}] with opening_balances = {'asset:cash': '50.00'} should return {'asset:cash': Decimal('150.00'), 'revenue:sales': Decimal('100.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _q(amount):\n return Decimal(amount).quantize(CENT, rounding=ROUND_HALF_UP)\n\nNORMAL_DEBIT_PREFIXES = ('asset:', 'expense:')\n\ndef post_entries(entries, opening_balances):\n balances = {}\n for acct, amt in (opening_balances or {}).items():\n balances[acct] = _q(amt)\n\n for entry in entries:\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for account, debit, credit in entry['lines']:\n d = _q(debit)\n c = _q(credit)\n if d != 0 and c != 0:\n raise ValueError(f\"invalid line in entry '{entry.get('memo', '')}': both debit and credit nonzero\")\n total_debits += d\n total_credits += c\n if total_debits != total_credits:\n raise ValueError(f\"unbalanced entry '{entry.get('memo', '')}': debits {total_debits} != credits {total_credits}\")\n\n for account, debit, credit in entry['lines']:\n d = _q(debit)\n c = _q(credit)\n if account.startswith(NORMAL_DEBIT_PREFIXES):\n delta = d - c\n else:\n delta = c - d\n balances[account] = _q(balances.get(account, Decimal('0')) + delta)\n\n return {acct: _q(bal) for acct, bal in balances.items()}\n\nif __name__ == '__main__':\n from decimal import Decimal\n entries = [\n {'date': '2024-01-01', 'memo': 'sale',\n 'lines': [('asset:cash', '100.00', '0'), ('revenue:sales', '0', '100.00')]},\n {'date': '2024-01-02', 'memo': 'pay rent',\n 'lines': [('expense:rent', '40.00', '0'), ('asset:cash', '0', '40.00')]},\n ]\n result = post_entries(entries, {'asset:cash': '50.00'})\n print(result)\n assert result == {'asset:cash': Decimal('110.00'),\n 'revenue:sales': Decimal('100.00'),\n 'expense:rent': Decimal('40.00')}\n print('All checks passed.')"}], "meta": {"idx": 2327, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 813, "latency_s": 11.5}} +{"prompt": [{"role": "user", "content": "Write a function `compute_payroll(hours, hourly_rate, federal_rate, state_rate, pretax_deductions, posttax_deductions)` that computes a single employee's net paycheck using precise Decimal arithmetic. Gross pay is hours times hourly_rate. Taxable wages are gross pay minus pretax_deductions (floor at zero). Federal tax is federal_rate percent of taxable wages, and state tax is state_rate percent of taxable wages. Net pay is gross pay minus both taxes minus posttax_deductions. All money amounts must be rounded to exactly 2 decimal places using ROUND_HALF_UP (banker's rounding is not acceptable for this payroll). Return a dict with keys 'gross_pay', 'federal_tax', 'state_tax', 'net_pay' as strings formatted like '1234.56'. Example: compute_payroll(Decimal('80'), Decimal('25.50'), Decimal('15'), Decimal('5'), Decimal('120.00'), Decimal('50.00')) should return {'gross_pay': '2040.00', 'federal_tax': '288.00', 'state_tax': '96.00', 'net_pay': '1606.00'} because taxable wages are 1920.00, federal tax is 288.00, state tax is 96.00, and 2040.00 - 288.00 - 96.00 - 50.00 = 1606.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _money(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef compute_payroll(hours, hourly_rate, federal_rate, state_rate,\n pretax_deductions, posttax_deductions):\n hours = Decimal(str(hours))\n hourly_rate = Decimal(str(hourly_rate))\n federal_rate = Decimal(str(federal_rate))\n state_rate = Decimal(str(state_rate))\n pretax_deductions = Decimal(str(pretax_deductions))\n posttax_deductions = Decimal(str(posttax_deductions))\n\n gross = hours * hourly_rate\n taxable = max(Decimal('0'), gross - pretax_deductions)\n federal_tax = taxable * federal_rate / Decimal('100')\n state_tax = taxable * state_rate / Decimal('100')\n\n gross = _money(gross)\n federal_tax = _money(federal_tax)\n state_tax = _money(state_tax)\n\n net = gross - federal_tax - state_tax - posttax_deductions\n net = _money(net)\n\n return {\n 'gross_pay': str(gross),\n 'federal_tax': str(federal_tax),\n 'state_tax': str(state_tax),\n 'net_pay': str(net),\n }\n\n\nif __name__ == '__main__':\n result = compute_payroll(Decimal('80'), Decimal('25.50'),\n Decimal('15'), Decimal('5'),\n Decimal('120.00'), Decimal('50.00'))\n assert result == {'gross_pay': '2040.00', 'federal_tax': '288.00',\n 'state_tax': '96.00', 'net_pay': '1606.00'}, result\n print(result)"}], "meta": {"idx": 2330, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 656, "latency_s": 5.6}} +{"prompt": [{"role": "user", "content": "You are given a CSV file of ledger transactions with columns: date (YYYY-MM-DD), account (non-empty string), description (string), amount (decimal number, positive for debit, negative for credit). Write a program that (1) reads the CSV, skipping a single header row; (2) validates each row: date must parse as a real calendar date, account must be non-empty, amount must parse as a valid Decimal with at most 2 decimal places; (3) collects all invalid rows with a reason string; (4) if the sum of all valid amounts is not exactly zero, abort with a message 'LEDGER OUT OF BALANCE' and the imbalance; (5) otherwise, sort valid rows by date (stable, preserving input order for equal dates) and write them to a new CSV with columns date, account, description, amount, balance, where balance is the cumulative sum of amounts so far, formatted to exactly 2 decimal places. All monetary arithmetic must use Decimal. Example input: header 'date,account,description,amount' followed by rows '2024-01-15,Cash,Opening,100.00', '2024-01-15,Revenue,Sale,-100.00', and an invalid row '2024-13-01,Bad,Wrong date,5.00'. Expected output: invalid rows list containing the bad row with reason 'invalid date', and the exported CSV has the two valid rows with balances 100.00 and 0.00. Implement this as a function process_ledger(in_path, out_path) returning the list of (row, reason) tuples for invalid rows."}], "completion": [{"role": "assistant", "content": "import csv\nfrom datetime import date\nfrom decimal import Decimal, InvalidOperation\n\n\ndef process_ledger(in_path, out_path):\n invalid_rows = []\n valid_rows = []\n\n with open(in_path, newline='', encoding='utf-8') as f:\n reader = csv.reader(f)\n rows = list(reader)\n\n for row in rows[1:]:\n if len(row) != 4:\n invalid_rows.append((row, 'wrong number of columns'))\n continue\n tx_date, account, description, amount_str = row\n\n try:\n date.fromisoformat(tx_date)\n except ValueError:\n invalid_rows.append((row, 'invalid date'))\n continue\n\n if not account.strip():\n invalid_rows.append((row, 'empty account'))\n continue\n\n try:\n amount = Decimal(amount_str)\n except InvalidOperation:\n invalid_rows.append((row, 'invalid amount'))\n continue\n\n if -amount.as_tuple().exponent > 2:\n invalid_rows.append((row, 'too many decimal places'))\n continue\n\n valid_rows.append((tx_date, account, description, amount))\n\n total = sum((r[3] for r in valid_rows), Decimal('0'))\n if total != 0:\n raise ValueError('LEDGER OUT OF BALANCE: {}'.format(total))\n\n valid_rows.sort(key=lambda r: r[0])\n\n with open(out_path, 'w', newline='', encoding='utf-8') as f:\n writer = csv.writer(f)\n writer.writerow(['date', 'account', 'description', 'amount', 'balance'])\n balance = Decimal('0.00')\n for tx_date, account, description, amount in valid_rows:\n balance += amount\n writer.writerow([\n tx_date,\n account,\n description,\n format(amount, '.2f'),\n format(balance, '.2f'),\n ])\n\n return invalid_rows\n\n\nif __name__ == '__main__':\n with open('ledger_in.csv', 'w', newline='', encoding='utf-8') as f:\n f.write('date,account,description,amount\\n')\n f.write('2024-01-15,Cash,Opening,100.00\\n')\n f.write('2024-01-15,Revenue,Sale,-100.00\\n')\n f.write('2024-13-01,Bad,Wrong date,5.00\\n')\n bad = process_ledger('ledger_in.csv', 'ledger_out.csv')\n print('Invalid rows:', bad)\n with open('ledger_out.csv', newline='', encoding='utf-8') as f:\n print(f.read())"}], "meta": {"idx": 2325, "topic": "transaction CSV import, validation, and export", "difficulty": "medium", "provider": "deepinfra", "in_tokens": 200, "out_tokens": 1017, "latency_s": 7.2}} +{"prompt": [{"role": "user", "content": "Implement a `Ledger` class that records accounting entries and produces a balanced trial balance report. Each entry has a description, a debit amount, and a credit amount, all handled with `Decimal` (quantized to 2 places, ROUND_HALF_UP). The class must support `add_entry(description, debit, credit)` which raises `ValueError` if the amounts are negative or if debit and credit are both zero. It must also support `total_debits()`, `total_credits()`, and `is_balanced()` \u2014 the ledger is balanced when total debits equal total credits exactly. Finally, implement `trial_balance()` returning a string of one line per entry like `': debit credit '` followed by a summary line `'Totals: debit credit balanced='`, with all amounts formatted to two decimal places. For example, with entries ('Cash sale', '10.00', '0.00') and ('Revenue', '0.00', '10.00'), the trial balance ends with 'Totals: debit 10.00 credit 10.00 balanced=True'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _to_money(value):\n return Decimal(value).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\nclass Ledger:\n def __init__(self):\n self._entries = []\n\n def add_entry(self, description, debit, credit):\n d = _to_money(debit)\n c = _to_money(credit)\n if d < 0 or c < 0:\n raise ValueError('Amounts must be non-negative')\n if d == 0 and c == 0:\n raise ValueError('Debit and credit cannot both be zero')\n self._entries.append((description, d, c))\n\n def total_debits(self):\n return sum((e[1] for e in self._entries), Decimal('0.00'))\n\n def total_credits(self):\n return sum((e[2] for e in self._entries), Decimal('0.00'))\n\n def is_balanced(self):\n return self.total_debits() == self.total_credits()\n\n def trial_balance(self):\n lines = [\n '{}: debit {} credit {}'.format(desc, d, c)\n for desc, d, c in self._entries\n ]\n lines.append(\n 'Totals: debit {} credit {} balanced={}'.format(\n self.total_debits(), self.total_credits(), self.is_balanced()\n )\n )\n return '\\n'.join(lines)\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add_entry('Cash sale', '10.00', '0.00')\n ledger.add_entry('Revenue', '0.00', '10.00')\n print(ledger.trial_balance())\n assert ledger.is_balanced() is True\n assert ledger.total_debits() == Decimal('10.00')\n assert ledger.total_credits() == Decimal('10.00')\n print('All checks passed.')"}], "meta": {"idx": 2332, "topic": "unit tests for accounting functions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 662, "latency_s": 6.4}} +{"prompt": [{"role": "user", "content": "Implement an accounting ledger using dataclasses and Decimal arithmetic. Define a `LedgerEntry` dataclass with fields `date` (ISO string 'YYYY-MM-DD'), `description` (str), `debit` (Decimal, default 0), `credit` (Decimal, default 0), and a `postings` tuple of (account_name, Decimal amount) pairs. Define a `Ledger` class that accepts a `precision` (int, default 2) and supports `add(entry)` and `balance(account)` methods. The `balance` method returns the net amount for an account, where postings with positive amounts are debits and negative amounts are credits, rounded to the ledger precision using ROUND_HALF_UP. The ledger must also support `validate()`, which raises `ValueError` if any entry's postings do not sum to exactly (debit - credit). Example: an entry with debit=Decimal('100.00'), credit=Decimal('0.00'), and postings (('cash', Decimal('100.00')), ('revenue', Decimal('-100.00'))) is valid, since 100.00 + (-100.00) == 0.00. Given entries adding ('2024-01-01','sale',Decimal('150.00'),Decimal('0.00'),(('cash',Decimal('150.00')),('revenue',Decimal('-150.00')))) and ('2024-01-02','buy supplies',Decimal('0.00'),Decimal('30.50'),(('supplies',Decimal('30.50')),('cash',Decimal('-30.50')))), ledger.balance('cash') should return Decimal('119.50')."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Tuple\n\n\n@dataclass\nclass LedgerEntry:\n date: str\n description: str\n debit: Decimal = Decimal('0')\n credit: Decimal = Decimal('0')\n postings: Tuple[Tuple[str, Decimal], ...] = ()\n\n\n@dataclass\nclass Ledger:\n precision: int = 2\n entries: list = field(default_factory=list)\n\n def add(self, entry: LedgerEntry) -> None:\n self.entries.append(entry)\n\n def balance(self, account: str) -> Decimal:\n quant = Decimal(1).scaleb(-self.precision)\n total = sum((amt for e in self.entries for name, amt in e.postings if name == account), Decimal('0'))\n return total.quantize(quant, rounding=ROUND_HALF_UP)\n\n def validate(self) -> None:\n for i, e in enumerate(self.entries):\n posting_sum = sum((amt for _, amt in e.postings), Decimal('0'))\n expected = e.debit - e.credit\n if posting_sum != expected:\n raise ValueError(f'Entry {i} ({e.description!r}) unbalanced: postings sum {posting_sum} != debit-credit {expected}')\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add(LedgerEntry('2024-01-01', 'sale', Decimal('150.00'), Decimal('0.00'),\n (('cash', Decimal('150.00')), ('revenue', Decimal('-150.00')))))\n ledger.add(LedgerEntry('2024-01-02', 'buy supplies', Decimal('0.00'), Decimal('30.50'),\n (('supplies', Decimal('30.50')), ('cash', Decimal('-30.50')))))\n ledger.validate()\n assert ledger.balance('cash') == Decimal('119.50')\n assert ledger.balance('revenue') == Decimal('-150.00')\n assert ledger.balance('supplies') == Decimal('30.50')\n print('All checks passed:', ledger.balance('cash'))"}], "meta": {"idx": 2333, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 779, "latency_s": 6.9}} +{"prompt": [{"role": "user", "content": "You are maintaining a small ledger for a business. Each transaction is recorded as a dict with an id, a description, and an amount (a Decimal, positive for debits/expenses, negative for credits/income). Sometimes a transaction is recorded incorrectly; the fix is done by a 'reversal' entry with the same magnitude but opposite sign, followed by a new corrected entry, or by 'voiding' the transaction entirely. Write a function `apply_corrections(transactions, corrections)` where `transactions` is a list of transaction dicts (each with keys 'id', 'description', 'amount') and `corrections` is a list of dicts, each with keys 'action' (either 'reverse' or 'void'), 'ref_id' (the id of the original transaction), and optionally 'replacement' (a dict with 'id', 'description', 'amount') for a 'reverse' action. A 'reverse' correction removes the original transaction, adds a reversal entry (same description prefixed with 'REVERSAL: ', negated amount, new id formed as ref_id + '-R'), and adds the replacement entry if provided. A 'void' correction removes the transaction and adds no new entries. The function should return a new list of transactions in their original order (with corrections applied) and also compute the final ledger balance, which is the sum of all amounts rounded to 2 decimal places using ROUND_HALF_UP. If a correction references a nonexistent id, raise a ValueError. Example: transactions = [{'id':'T1','description':'Office supplies','amount':Decimal('50.00')}, {'id':'T2','description':'Sales income','amount':Decimal('-120.50')}] with corrections = [{'action':'reverse','ref_id':'T1','replacement':{'id':'T3','description':'Office supplies (corrected)','amount':Decimal('45.00')}}] should produce the list [T2 entry, REVERSAL of T1, T3 entry] and a final balance of Decimal('-75.50')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef apply_corrections(transactions, corrections):\n \"\"\"Apply reversal and void corrections to a ledger.\n\n Returns (new_transactions, final_balance) where final_balance is a\n Decimal rounded to 2 places with ROUND_HALF_UP.\n \"\"\"\n txns = [dict(t) for t in transactions]\n\n for corr in corrections:\n action = corr['action']\n ref_id = corr['ref_id']\n\n # Locate the referenced transaction.\n idx = None\n for i, t in enumerate(txns):\n if t['id'] == ref_id:\n idx = i\n break\n if idx is None:\n raise ValueError(f\"Unknown transaction id: {ref_id}\")\n\n original = txns[idx]\n\n if action == 'void':\n txns.pop(idx)\n elif action == 'reverse':\n reversal = {\n 'id': ref_id + '-R',\n 'description': 'REVERSAL: ' + original['description'],\n 'amount': -original['amount'],\n }\n replacement_entries = [reversal]\n if 'replacement' in corr and corr['replacement'] is not None:\n replacement_entries.append(dict(corr['replacement']))\n txns[idx:idx + 1] = replacement_entries\n else:\n raise ValueError(f\"Unknown action: {action}\")\n\n balance = sum((t['amount'] for t in txns), Decimal('0'))\n balance = balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return txns, balance\n\n\nif __name__ == '__main__':\n transactions = [\n {'id': 'T1', 'description': 'Office supplies', 'amount': Decimal('50.00')},\n {'id': 'T2', 'description': 'Sales income', 'amount': Decimal('-120.50')},\n ]\n corrections = [\n {\n 'action': 'reverse',\n 'ref_id': 'T1',\n 'replacement': {\n 'id': 'T3',\n 'description': 'Office supplies (corrected)',\n 'amount': Decimal('45.00'),\n },\n }\n ]\n new_txns, balance = apply_corrections(transactions, corrections)\n for t in new_txns:\n print(t['id'], t['description'], t['amount'])\n print('Balance:', balance)\n assert balance == Decimal('-75.50')"}], "meta": {"idx": 2331, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 1030, "latency_s": 7.7}} +{"prompt": [{"role": "user", "content": "You are given a list of journal entries for a small business, where each entry is a tuple (date, account, debit, credit) with amounts as strings. Accounts are either expense accounts (start with 'Exp:'), income accounts (start with 'Inc:'), asset accounts ('Asset:'), liability accounts ('Liab:'), or equity accounts ('Equity:'). Write a function `summarize(entries)` that returns a tuple (net_income, total_assets, total_liabilities_equity) of Decimal values rounded to 2 decimal places with ROUND_HALF_UP. Net income is total income minus total expenses. Total assets is the sum of net debit balances of asset accounts (debits minus credits). Total liabilities and equity is the sum of net credit balances of liability and equity accounts plus net income (retained earnings). For example, entries = [('2024-01-05','Inc:Sales','0','120.005'), ('2024-01-10','Exp:Rent','80.00','0'), ('2024-01-15','Asset:Cash','100.005','0'), ('2024-02-01','Liab:Loan','0','20.00'), ('2024-02-02','Equity:Capital','0','0.005')] should return (Decimal('40.01'), Decimal('100.01'), Decimal('100.01')) because income 120.01 (rounded from 120.005), expenses 80.00, net income 40.01; assets 100.01; and liabilities+equity+net income = 20.00 + 0.01 + 40.01 = 60.02... note that if liabilities+equity+net income does not equal total assets, instead set total_liabilities_equity equal to total_assets so the balance sheet balances (assume any residual is due to unrecorded retained earnings)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\ndef summarize(entries):\n def r2(x):\n return x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n income = Decimal('0')\n expenses = Decimal('0')\n assets = Decimal('0')\n liab_eq = Decimal('0')\n\n for date, account, debit, credit in entries:\n d = Decimal(debit)\n c = Decimal(credit)\n net = d - c\n if account.startswith('Inc:'):\n income += c - d\n elif account.startswith('Exp:'):\n expenses += d - c\n elif account.startswith('Asset:'):\n assets += net\n elif account.startswith('Liab:') or account.startswith('Equity:'):\n liab_eq += -net\n\n net_income = r2(income - expenses)\n total_assets = r2(assets)\n total_le = r2(liab_eq) + net_income\n if total_le != total_assets:\n total_le = total_assets\n return (net_income, total_assets, total_le)\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-05', 'Inc:Sales', '0', '120.005'),\n ('2024-01-10', 'Exp:Rent', '80.00', '0'),\n ('2024-01-15', 'Asset:Cash', '100.005', '0'),\n ('2024-02-01', 'Liab:Loan', '0', '20.00'),\n ('2024-02-02', 'Equity:Capital', '0', '0.005'),\n ]\n result = summarize(entries)\n assert result == (Decimal('40.01'), Decimal('100.01'), Decimal('100.01')), result\n print(result)"}], "meta": {"idx": 2338, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 736, "latency_s": 9.6}} +{"prompt": [{"role": "user", "content": "A bookkeeper needs a simple budget-versus-actual variance report. Write a function `variance_report(budget, actual)` that takes two dictionaries mapping account names (strings) to monetary amounts (values may be given as Decimal, int, or float) and returns a dictionary mapping each account name to a 2-tuple `(variance, variance_pct)`. The variance is `budget - actual`, computed with Decimal and quantized to 2 decimal places with ROUND_HALF_UP. The variance percentage is the variance divided by the budget, expressed as a Decimal quantized to 2 decimal places, using ROUND_HALF_UP; if the budget is zero, the percentage should be Decimal('0.00'). Include every account that appears in either dictionary (a missing side is treated as 0.00). For example, with budget = {'rent': 1200, 'supplies': 250} and actual = {'rent': 1350, 'utilities': 80}, the result should include 'rent': (Decimal('-150.00'), Decimal('-12.50')), 'supplies': (Decimal('250.00'), Decimal('100.00')), and 'utilities': (Decimal('-80.00'), Decimal('-100.00')). Also include a small demo under `if __name__ == '__main__':` that prints the report for this example, sorted by account name, one account per line in the form `account: variance variance_pct%`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _to_decimal(value):\n if isinstance(value, Decimal):\n return value\n if isinstance(value, float):\n return Decimal(str(value))\n return Decimal(value)\n\ndef _q(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef variance_report(budget, actual):\n accounts = sorted(set(budget) | set(actual))\n report = {}\n for account in accounts:\n b = _to_decimal(budget.get(account, 0))\n a = _to_decimal(actual.get(account, 0))\n variance = _q(b - a)\n if b == 0:\n pct = Decimal('0.00')\n else:\n pct = _q((b - a) / b * 100)\n report[account] = (variance, pct)\n return report\n\nif __name__ == '__main__':\n budget = {'rent': 1200, 'supplies': 250}\n actual = {'rent': 1350, 'utilities': 80}\n report = variance_report(budget, actual)\n for account in sorted(report):\n variance, pct = report[account]\n print(f\"{account}: {variance} {pct}%\")"}], "meta": {"idx": 2339, "topic": "budget versus actual variance analysis", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 579, "latency_s": 5.4}} +{"prompt": [{"role": "user", "content": "Implement a small ledger module and its unit tests. The ledger keeps a starting balance and supports applying debit and credit entries, each given as a string amount with exactly two decimal places (e.g. \"125.50\"). All monetary math must use Decimal with ROUND_HALF_UP rounding to cents. Implement a function `apply_entries(starting_balance: str, entries: list[str]) -> str` where each entry is a string like \"debit 10.25\" or \"credit 5.10\"; a debit subtracts and a credit adds. The result is the final balance formatted to two decimal places (e.g. \"115.85\"). If any amount is negative, has more than two decimals, or the entry format is invalid, raise ValueError. Then write unit tests using unittest covering: a normal mix of credits and debits (starting \"100.00\", entries [\"credit 5.10\", \"debit 10.25\"] should yield \"94.85\"), rounding behavior (credit \"0.005\"-style inputs are invalid, but credit \"0.01\" twice on \"0.00\" yields \"0.02\"), error cases (negative amount, three decimal places, malformed entry), and an empty entry list returning the starting balance unchanged."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom decimal import Decimal, ROUND_HALF_UP\nimport re\n\nENTRY_RE = re.compile(r\"^(debit|credit) (\\d+\\.\\d{2})$\")\n\n\ndef apply_entries(starting_balance: str, entries: list) -> str:\n m = ENTRY_RE.match(\"__placeholder__\") # unused, kept for clarity\n bal = Decimal(starting_balance)\n if bal != bal.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP):\n raise ValueError(\"starting balance must have at most two decimals\")\n if bal < 0:\n raise ValueError(\"starting balance must be non-negative\")\n for entry in entries:\n m = ENTRY_RE.match(entry)\n if not m:\n raise ValueError(\"invalid entry: %r\" % entry)\n kind, amount_str = m.groups()\n amount = Decimal(amount_str)\n if kind == \"debit\":\n bal -= amount\n else:\n bal += amount\n return str(bal.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP))\n\n\nclass TestApplyEntries(unittest.TestCase):\n def test_mixed_credits_and_debits(self):\n self.assertEqual(\n apply_entries(\"100.00\", [\"credit 5.10\", \"debit 10.25\"]),\n \"94.85\",\n )\n\n def test_small_amounts_add_up(self):\n self.assertEqual(apply_entries(\"0.00\", [\"credit 0.01\", \"credit 0.01\"]), \"0.02\")\n\n def test_empty_entries_returns_starting_balance(self):\n self.assertEqual(apply_entries(\"75.00\", []), \"75.00\")\n\n def test_negative_amount_rejected(self):\n with self.assertRaises(ValueError):\n apply_entries(\"100.00\", [\"debit -10.00\"])\n\n def test_three_decimals_rejected(self):\n with self.assertRaises(ValueError):\n apply_entries(\"100.00\", [\"credit 5.125\"])\n\n def test_malformed_entry_rejected(self):\n with self.assertRaises(ValueError):\n apply_entries(\"100.00\", [\"pay 5.00\"])\n\n def test_extra_whitespace_rejected(self):\n with self.assertRaises(ValueError):\n apply_entries(\"100.00\", [\"credit 5.00\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()"}], "meta": {"idx": 2340, "topic": "unit tests for accounting functions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 809, "latency_s": 6.8}} +{"prompt": [{"role": "user", "content": "You are maintaining a small sales ledger. Given a list of net (pre-tax) amounts as strings, compute the gross amount for each entry by applying a fixed VAT rate of 8.5% (given as a Decimal string '0.085'). For each entry, the VAT must be rounded to exactly 2 decimal places using ROUND_HALF_UP. The program should print, for each entry, a line 'net=NET vat=VAT gross=GROSS' with all values shown to 2 decimals, and then a final line 'total_gross=SUM' where SUM is the sum of the gross amounts (also to 2 decimals). For example, input entries ['10.00', '0.05', '3.33'] produce VAT of 0.85, 0.00 (0.00425 rounds to 0.00), and 0.28 (0.28305 rounds to 0.28), giving gross amounts 10.85, 0.05, and 3.61, and total_gross=14.51. Write a function compute_vat_ledger(entries) that returns the list of (net, vat, gross) Decimal tuples, and a main section that prints the report for the example input."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\nVAT_RATE = Decimal('0.085')\n\n\ndef compute_vat_ledger(entries):\n results = []\n for entry in entries:\n net = Decimal(entry)\n vat = (net * VAT_RATE).quantize(TWO, rounding=ROUND_HALF_UP)\n gross = net + vat\n results.append((net, vat, gross))\n return results\n\n\ndef main():\n entries = ['10.00', '0.05', '3.33']\n rows = compute_vat_ledger(entries)\n total_gross = Decimal('0.00')\n for net, vat, gross in rows:\n total_gross += gross\n print(f\"net={net.quantize(TWO)} vat={vat.quantize(TWO)} gross={gross.quantize(TWO)}\")\n print(f\"total_gross={total_gross.quantize(TWO)}\")\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2341, "topic": "sales tax and VAT computation and rounding", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 422, "latency_s": 2.4}} +{"prompt": [{"role": "user", "content": "You are reconciling a monthly bank statement against your internal ledger. Given a list of ledger entries and a list of bank statement entries (each entry is a tuple of (description, amount) where positive amounts are deposits and negative are withdrawals), identify matched pairs, compute the ledger balance, the bank balance, and report any unmatched entries. Two entries match if they have the same description and the same amount. Use Decimal for all monetary arithmetic. Output a reconciliation report as a dictionary with keys: 'ledger_balance', 'bank_balance', 'unmatched_ledger', 'unmatched_bank' (lists of tuples). Example: ledger = [('Deposit', '500.00'), ('Rent', '-1200.00'), ('Coffee', '-4.50')], bank = [('Deposit', '500.00'), ('Payroll', '1500.00'), ('Coffee', '-4.50')] should give ledger_balance = -704.50, bank_balance = 1995.50, unmatched_ledger = [('Rent', '-1200.00')], unmatched_bank = [('Payroll', '1500.00')]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom collections import Counter\n\ndef reconcile(ledger, bank):\n ledger = [(d, Decimal(a)) for d, a in ledger]\n bank = [(d, Decimal(a)) for d, a in bank]\n\n ledger_counts = Counter(ledger)\n bank_counts = Counter(bank)\n\n common = ledger_counts & bank_counts\n\n unmatched_ledger = sorted((ledger_counts - common).elements())\n unmatched_bank = sorted((bank_counts - common).elements())\n\n ledger_balance = sum((a for _, a in ledger), Decimal('0'))\n bank_balance = sum((a for _, a in bank), Decimal('0'))\n\n return {\n 'ledger_balance': ledger_balance,\n 'bank_balance': bank_balance,\n 'unmatched_ledger': unmatched_ledger,\n 'unmatched_bank': unmatched_bank,\n }\n\nif __name__ == '__main__':\n ledger = [('Deposit', '500.00'), ('Rent', '-1200.00'), ('Coffee', '-4.50')]\n bank = [('Deposit', '500.00'), ('Payroll', '1500.00'), ('Coffee', '-4.50')]\n report = reconcile(ledger, bank)\n print(report)\n assert report['ledger_balance'] == Decimal('-704.50')\n assert report['bank_balance'] == Decimal('1995.50')\n assert report['unmatched_ledger'] == [('Rent', Decimal('-1200.00'))]\n assert report['unmatched_bank'] == [('Payroll', Decimal('1500.00'))]\n print('All checks passed.')"}], "meta": {"idx": 2342, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 567, "latency_s": 5.6}} +{"prompt": [{"role": "user", "content": "Write a function `validate_journal_entry(lines)` that checks whether a journal entry obeys double-entry rules. Each line is a tuple `(account, debit, credit)` where `debit` and `credit` are Decimal amounts (or strings convertible to Decimal). The function must: (1) reject any line where both debit and credit are non-zero or both are zero (each line must affect exactly one side), (2) reject negative amounts, and (3) reject the entry if total debits do not equal total credits. Return a tuple `(is_valid, message)`: `(True, \"entry balanced\")` on success, otherwise `(False, reason)` where reason is one of \"line N invalid\", \"line N negative\", or \"debits and credits do not balance\". Use Decimal for all arithmetic. Example: lines = [('Cash', '100.00', '0'), ('Revenue', '0', '100.00')] returns (True, 'entry balanced'); lines = [('Cash', '50.00', '0'), ('Revenue', '0', '40.00')] returns (False, 'debits and credits do not balance')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\nZERO = Decimal('0')\n\ndef validate_journal_entry(lines):\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for i, line in enumerate(lines, start=1):\n account, debit, credit = line\n debit = debit if isinstance(debit, Decimal) else Decimal(str(debit))\n credit = credit if isinstance(credit, Decimal) else Decimal(str(credit))\n if debit < ZERO or credit < ZERO:\n return (False, \"line %d negative\" % i)\n if (debit == ZERO) == (credit == ZERO):\n return (False, \"line %d invalid\" % i)\n total_debits += debit\n total_credits += credit\n if total_debits != total_credits:\n return (False, \"debits and credits do not balance\")\n return (True, \"entry balanced\")\n\nif __name__ == \"__main__\":\n print(validate_journal_entry([('Cash', '100.00', '0'), ('Revenue', '0', '100.00')]))\n print(validate_journal_entry([('Cash', '50.00', '0'), ('Revenue', '0', '40.00')]))\n print(validate_journal_entry([('Cash', '10', '10'), ('Revenue', '0', '20')]))\n print(validate_journal_entry([('Cash', '-5', '0'), ('Revenue', '0', '5')]))"}], "meta": {"idx": 2343, "topic": "double-entry journal entries and posting rules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 539, "latency_s": 18.2}} +{"prompt": [{"role": "user", "content": "Implement an invoice numbering and parsing system for a small bookkeeping office. Invoice numbers follow the format INV-YYYY-NNNN where YYYY is the invoice year and NNNN is a zero-padded 4-digit sequence number (0001-9999) unique within a year. Write a class InvoiceRegister that supports: (1) next_number(year) which returns the next available invoice number string for the given year, using Decimal-safe money handling when recording amounts; (2) record(number, customer, amount) which registers an invoice with a Decimal amount rounded to 2 places (ROUND_HALF_UP), raising ValueError if the number is malformed, the year's sequence already exists, or the amount is negative; (3) total(year) which returns the total invoiced amount for a year as a Decimal with exactly 2 decimal places; and (4) parse(number) which returns a tuple (year, seq) as integers, raising ValueError if the format is invalid (e.g., 'INV-20-0001', 'INV-2023-12', 'INV-2023-0000', 'INV-2023-10000'). Example: after record('INV-2024-0001','Acme',Decimal('100.005')) and record('INV-2024-0002','Beta',Decimal('49.99')), total(2024) must equal Decimal('150.00'), and next_number(2024) must return 'INV-2024-0003'."}], "completion": [{"role": "assistant", "content": "import re\nfrom decimal import Decimal, ROUND_HALF_UP\n\n\nclass InvoiceRegister:\n _PATTERN = re.compile(r'^INV-(\\d{4})-(\\d{4})$')\n\n def __init__(self):\n self._invoices = {} # year -> {seq: (customer, Decimal amount)}\n\n @staticmethod\n def parse(number):\n if not isinstance(number, str):\n raise ValueError('invoice number must be a string')\n m = InvoiceRegister._PATTERN.match(number)\n if not m:\n raise ValueError('malformed invoice number: %r' % number)\n year = int(m.group(1))\n seq = int(m.group(2))\n if seq == 0:\n raise ValueError('sequence number must be 0001-9999')\n return year, seq\n\n def next_number(self, year):\n if not isinstance(year, int) or not (1000 <= year <= 9999):\n raise ValueError('year must be a 4-digit integer')\n used = self._invoices.get(year, {})\n seq = 1\n while seq in used:\n seq += 1\n if seq > 9999:\n raise ValueError('no available invoice numbers for year %d' % year)\n return 'INV-%04d-%04d' % (year, seq)\n\n def record(self, number, customer, amount):\n year, seq = self.parse(number)\n amount = Decimal(amount)\n if amount < 0:\n raise ValueError('amount must be non-negative')\n amount = amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n year_map = self._invoices.setdefault(year, {})\n if seq in year_map:\n raise ValueError('duplicate invoice number: %s' % number)\n year_map[seq] = (customer, amount)\n\n def total(self, year):\n entries = self._invoices.get(year, {})\n total = sum((amt for _, amt in entries.values()), Decimal('0'))\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n reg = InvoiceRegister()\n reg.record('INV-2024-0001', 'Acme', Decimal('100.005'))\n reg.record('INV-2024-0002', 'Beta', Decimal('49.99'))\n assert reg.total(2024) == Decimal('150.00')\n assert reg.next_number(2024) == 'INV-2024-0003'\n assert InvoiceRegister.parse('INV-2023-0042') == (2023, 42)\n for bad in ['INV-20-0001', 'INV-2023-12', 'INV-2023-0000', 'INV-2023-10000']:\n try:\n InvoiceRegister.parse(bad)\n raise AssertionError('should have failed: %s' % bad)\n except ValueError:\n pass\n print('all checks passed')"}], "meta": {"idx": 2344, "topic": "invoice generation, numbering, and parsing", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 923, "latency_s": 9.4}} +{"prompt": [{"role": "user", "content": "Write a function aging_report(entries, as_of) that produces an aging summary for a combined accounts receivable and payable ledger. Each entry is a dict with keys 'id' (str), 'type' ('AR' or 'AP'), 'due_date' (datetime.date), and 'amount' (Decimal, positive). An entry is open (unpaid) unless its 'id' appears in the list 'paid_ids' passed via entries as a key 'paid' (a list of ids, default empty). For each open entry, bucket its amount by days overdue relative to as_of: 'current' if due_date >= as_of, '1-30' if 0 <= (as_of - due_date).days <= 30, '31-60' if 31-60 days, '61-90' if 61-90 days, and 'over90' if more than 90 days. Return a dict mapping type ('AR'/'AP') to a dict of the five bucket names to Decimal totals (quantized to 2 places, ROUND_HALF_UP), always including all five buckets even if zero. Example: entries = [{'id':'INV1','type':'AR','due_date':date(2024,6,1),'amount':Decimal('100.00')}, {'id':'BILL1','type':'AP','due_date':date(2024,7,15),'amount':Decimal('50.50')}], as_of=date(2024,7,1) gives AR {'current': Decimal('0.00'), '1-30': Decimal('100.00'), '31-60': Decimal('0.00'), '61-90': Decimal('0.00'), 'over90': Decimal('0.00')} and AP {'current': Decimal('50.50'), ...zeros...} because INV1 is 30 days overdue and BILL1 is not yet due."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\n\ndef aging_report(entries, as_of):\n buckets = ['current', '1-30', '31-60', '61-90', 'over90']\n result = {\n 'AR': {b: Decimal('0.00') for b in buckets},\n 'AP': {b: Decimal('0.00') for b in buckets},\n }\n paid = set(entries.get('paid', [])) if isinstance(entries, dict) else set()\n items = entries.get('entries', []) if isinstance(entries, dict) else entries\n for e in items:\n if e['id'] in paid:\n continue\n days_over = (as_of - e['due_date']).days\n if days_over <= 0:\n bucket = 'current'\n elif days_over <= 30:\n bucket = '1-30'\n elif days_over <= 60:\n bucket = '31-60'\n elif days_over <= 90:\n bucket = '61-90'\n else:\n bucket = 'over90'\n result[e['type']][bucket] += e['amount']\n for t in result:\n for b in result[t]:\n result[t][b] = result[t][b].quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return result\n\n\nif __name__ == '__main__':\n entries = [\n {'id': 'INV1', 'type': 'AR', 'due_date': date(2024, 6, 1), 'amount': Decimal('100.00')},\n {'id': 'BILL1', 'type': 'AP', 'due_date': date(2024, 7, 15), 'amount': Decimal('50.50')},\n ]\n print(aging_report(entries, date(2024, 7, 1)))\n entries2 = {\n 'entries': [\n {'id': 'INV2', 'type': 'AR', 'due_date': date(2024, 4, 1), 'amount': Decimal('25.255')},\n {'id': 'INV1', 'type': 'AR', 'due_date': date(2024, 6, 1), 'amount': Decimal('100.00')},\n ],\n 'paid': ['INV1'],\n }\n print(aging_report(entries2, date(2024, 7, 1)))"}], "meta": {"idx": 2336, "topic": "accounts receivable and payable aging reports", "difficulty": "medium", "provider": "novita", "in_tokens": 199, "out_tokens": 980, "latency_s": 10.8}} +{"prompt": [{"role": "user", "content": "A small bookkeeping firm pays its sales agents a commission on each sale and also records a tip that must be split between two assistants. Write a function `record_sale(agent_name, gross_amount, commission_rate, tip_amount)` that returns a dictionary describing the ledger entry for one sale. The commission is `gross_amount * commission_rate`, rounded to 2 decimal places using Decimal ROUND_HALF_UP. The tip is split evenly between two assistants; if the tip does not divide evenly into cents, the first assistant gets the extra cent (the two tip shares must each be exact cents and sum to the tip). The agent's net payout is the commission, and the firm's remaining balance is `gross_amount - commission - tip`. Return a dict with keys 'agent', 'commission', 'tip_share_1', 'tip_share_2', 'firm_balance', all values as Decimal cents. Example: record_sale('Ann', Decimal('100.00'), Decimal('0.05'), Decimal('5.01')) should return {'agent': 'Ann', 'commission': Decimal('5.00'), 'tip_share_1': Decimal('2.51'), 'tip_share_2': Decimal('2.50'), 'firm_balance': Decimal('89.99')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef record_sale(agent_name, gross_amount, commission_rate, tip_amount):\n cents = Decimal('0.01')\n commission = (gross_amount * commission_rate).quantize(cents, rounding=ROUND_HALF_UP)\n tip_cents = int((tip_amount / cents).to_integral_value(rounding=ROUND_HALF_UP))\n share1_cents = (tip_cents + 1) // 2\n share2_cents = tip_cents - share1_cents\n tip_share_1 = Decimal(share1_cents) * cents\n tip_share_2 = Decimal(share2_cents) * cents\n firm_balance = (gross_amount - commission - tip_share_1 - tip_share_2).quantize(cents, rounding=ROUND_HALF_UP)\n return {\n 'agent': agent_name,\n 'commission': commission,\n 'tip_share_1': tip_share_1,\n 'tip_share_2': tip_share_2,\n 'firm_balance': firm_balance,\n }\n\nif __name__ == '__main__':\n entry = record_sale('Ann', Decimal('100.00'), Decimal('0.05'), Decimal('5.01'))\n print(entry)\n assert entry == {\n 'agent': 'Ann',\n 'commission': Decimal('5.00'),\n 'tip_share_1': Decimal('2.51'),\n 'tip_share_2': Decimal('2.50'),\n 'firm_balance': Decimal('89.99'),\n }\n entry2 = record_sale('Bob', Decimal('49.99'), Decimal('0.075'), Decimal('3.00'))\n print(entry2)\n assert entry2['commission'] == Decimal('3.75')\n assert entry2['tip_share_1'] == Decimal('1.50')\n assert entry2['tip_share_2'] == Decimal('1.50')\n assert entry2['firm_balance'] == Decimal('43.24')\n print('All checks passed.')"}], "meta": {"idx": 2345, "topic": "commission, tip, and percentage splits", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 658, "latency_s": 5.5}} +{"prompt": [{"role": "user", "content": "Write a function `summarize(entries)` that turns a list of ledger entries into P&L and balance-sheet figures using Decimal arithmetic. Each entry is a tuple `(account, amount)` where account is one of 'cash', 'receivables', 'equipment', 'payables', 'revenue', 'expenses'. Asset and liability accounts (cash, receivables, equipment, payables) are balance-sheet accounts; revenue and expenses are P&L accounts. The function must return a dict with keys 'net_income' (revenue minus expenses), 'total_assets' (sum of cash, receivables, equipment), 'total_liabilities' (payables), and 'equity' (total_assets minus total_liabilities), all Decimal values rounded to 2 places with ROUND_HALF_UP. Example: entries = [('cash', '100.00'), ('revenue', '100.00'), ('payables', '50.00'), ('expenses', '10.00')] returns {'net_income': Decimal('90.00'), 'total_assets': Decimal('100.00'), 'total_liabilities': Decimal('50.00'), 'equity': Decimal('50.00')}. Negative balances should be kept as negative values."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize(entries):\n accounts = {\n 'cash': Decimal('0'),\n 'receivables': Decimal('0'),\n 'equipment': Decimal('0'),\n 'payables': Decimal('0'),\n 'revenue': Decimal('0'),\n 'expenses': Decimal('0'),\n }\n for account, amount in entries:\n if account not in accounts:\n raise ValueError('unknown account: %s' % account)\n accounts[account] += Decimal(amount)\n\n net_income = accounts['revenue'] - accounts['expenses']\n total_assets = accounts['cash'] + accounts['receivables'] + accounts['equipment']\n total_liabilities = accounts['payables']\n equity = total_assets - total_liabilities\n\n def round2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n return {\n 'net_income': round2(net_income),\n 'total_assets': round2(total_assets),\n 'total_liabilities': round2(total_liabilities),\n 'equity': round2(equity),\n }\n\n\nif __name__ == '__main__':\n entries = [\n ('cash', '100.00'),\n ('revenue', '100.00'),\n ('payables', '50.00'),\n ('expenses', '10.00'),\n ]\n result = summarize(entries)\n assert result == {\n 'net_income': Decimal('90.00'),\n 'total_assets': Decimal('100.00'),\n 'total_liabilities': Decimal('50.00'),\n 'equity': Decimal('50.00'),\n }\n print(result)"}], "meta": {"idx": 2346, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 623, "latency_s": 5.3}} +{"prompt": [{"role": "user", "content": "Write a function `variance_report(budget, actual)` that compares a monthly budget against actual spending and produces a variance report. Both inputs are dictionaries mapping account names (strings) to money amounts given as strings representing decimal dollars (e.g. '150.00'); accounts may appear in one dict but not the other, in which case treat the missing amount as '0.00'. All money must be handled with `decimal.Decimal` with cents precision, rounding with `ROUND_HALF_UP`. The function returns a list of tuples `(account, budget, actual, variance)` sorted by account name, where `variance = budget - actual` (positive means under budget, negative means over budget), each money value quantized to 2 decimal places. Example: budget = {'rent': '1200.00', 'supplies': '250.50'}, actual = {'rent': '1200.00', 'supplies': '310.75', 'travel': '90.00'} should return [('rent', Decimal('1200.00'), Decimal('1200.00'), Decimal('0.00')), ('supplies', Decimal('250.50'), Decimal('310.75'), Decimal('-60.25')), ('travel', Decimal('0.00'), Decimal('90.00'), Decimal('-90.00'))]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _to_money(value):\n if value is None:\n value = '0.00'\n return Decimal(str(value)).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef variance_report(budget, actual):\n accounts = sorted(set(budget) | set(actual))\n report = []\n for account in accounts:\n b = _to_money(budget.get(account))\n a = _to_money(actual.get(account))\n variance = (b - a).quantize(TWO, rounding=ROUND_HALF_UP)\n report.append((account, b, a, variance))\n return report\n\n\nif __name__ == '__main__':\n budget = {'rent': '1200.00', 'supplies': '250.50'}\n actual = {'rent': '1200.00', 'supplies': '310.75', 'travel': '90.00'}\n result = variance_report(budget, actual)\n expected = [\n ('rent', Decimal('1200.00'), Decimal('1200.00'), Decimal('0.00')),\n ('supplies', Decimal('250.50'), Decimal('310.75'), Decimal('-60.25')),\n ('travel', Decimal('0.00'), Decimal('90.00'), Decimal('-90.00')),\n ]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2347, "topic": "budget versus actual variance analysis", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 551, "latency_s": 4.7}} +{"prompt": [{"role": "user", "content": "Write a function `compute_net_pay(gross, federal_rate, state_rate, pre_tax_deductions, post_tax_deductions)` that computes a paycheck net pay for an employee. The gross pay and all deduction amounts are money values; the rates are percentages (e.g., 25.0 means 25%). Pre-tax deductions (like a 401k contribution) reduce taxable gross before taxes are computed, while post-tax deductions (like a garnishment) are subtracted after taxes. All monetary calculations must use `Decimal` with cents rounded half-up at each reporting step: taxable gross, federal withholding, state withholding, total deductions, and net pay. Federal and state withholding are each computed as the rounded product of the rate and taxable gross. Net pay equals rounded taxable gross minus rounded withholdings minus rounded post-tax deductions. Return a dict with keys 'taxable_gross', 'federal_withholding', 'state_withholding', 'total_deductions', 'net_pay', all Decimal values rounded to 2 decimal places. Example: gross=Decimal('3500.00'), federal_rate=Decimal('22'), state_rate=Decimal('5'), pre_tax=Decimal('300.00'), post_tax=Decimal('50.00') gives taxable_gross=3200.00, federal=704.00, state=160.00, total_deductions=1214.00, net_pay=2286.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round_cents(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef compute_net_pay(gross, federal_rate, state_rate, pre_tax_deductions, post_tax_deductions):\n gross = Decimal(str(gross))\n federal_rate = Decimal(str(federal_rate))\n state_rate = Decimal(str(state_rate))\n pre_tax_deductions = Decimal(str(pre_tax_deductions))\n post_tax_deductions = Decimal(str(post_tax_deductions))\n\n taxable_gross = _round_cents(gross - pre_tax_deductions)\n federal_withholding = _round_cents(taxable_gross * federal_rate / Decimal('100'))\n state_withholding = _round_cents(taxable_gross * state_rate / Decimal('100'))\n total_deductions = _round_cents(\n pre_tax_deductions + federal_withholding + state_withholding + post_tax_deductions\n )\n net_pay = _round_cents(\n taxable_gross - federal_withholding - state_withholding - post_tax_deductions\n )\n\n return {\n 'taxable_gross': taxable_gross,\n 'federal_withholding': federal_withholding,\n 'state_withholding': state_withholding,\n 'total_deductions': total_deductions,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = compute_net_pay(\n Decimal('3500.00'), Decimal('22'), Decimal('5'),\n Decimal('300.00'), Decimal('50.00')\n )\n for k, v in result.items():\n print(k, '=', v)\n assert result['taxable_gross'] == Decimal('3200.00')\n assert result['federal_withholding'] == Decimal('704.00')\n assert result['state_withholding'] == Decimal('160.00')\n assert result['total_deductions'] == Decimal('1214.00')\n assert result['net_pay'] == Decimal('2286.00')\n print('All checks passed.')"}], "meta": {"idx": 2348, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 759, "latency_s": 7.0}} +{"prompt": [{"role": "user", "content": "Acme Corp's fiscal year begins on April 1 (fiscal year 2025 runs 2025-04-01 through 2026-03-31), so fiscal quarters are the three-month blocks starting in April, July, October, and January. You are given a ledger as a list of entries, each a tuple (iso_date, debit, credit) where debit and credit are strings representing exact monetary amounts in dollars. Write a function quarterly_report(entries, fiscal_start_month=4) that groups the entries into fiscal quarters and, for each quarter touched by the ledger, returns a dict with keys: quarter (label like \"FY2025-Q1\", where the fiscal year is the calendar year in which it begins), start and end (ISO dates, where end is the month-end of the quarter's last month), opening_balance, total_debits, total_credits, closing_balance, and average_daily_balance \u2014 the day-weighted average balance over the quarter, where a balance applies from its entry date (inclusive) until the day before the next entry, and the final balance applies through the quarter end (inclusive). All monetary outputs must be Decimal values rounded half-up to cents. For example, with entries [(\"2025-04-01\", \"1000.00\", \"0.00\"), (\"2025-05-15\", \"0.00\", \"250.50\"), (\"2025-06-30\", \"100.00\", \"0.00\"), (\"2025-07-10\", \"300.00\", \"0.00\")], FY2025-Q1 (2025-04-01 to 2025-06-30, 91 days) has debits 1100.00, credits 250.50, closing balance 849.50, and average daily balance (44*1000.00 + 46*749.50 + 1*849.50)/91 = 871.72, while FY2025-Q2 (2025-07-01 to 2025-09-30, 92 days) has opening 849.50, debits 300.00, closing 1149.50, and average (9*849.50 + 83*1149.50)/92 = 1120.15."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\ndef money(value):\n \"\"\"Round a Decimal to cents using half-up rounding.\"\"\"\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef month_end(year, month):\n \"\"\"Return the last calendar day of the given month as a date.\"\"\"\n return date(year, month, calendar.monthrange(year, month)[1])\n\n\ndef quarter_bounds(d, fiscal_start_month):\n \"\"\"Given a date, return (label, quarter_start, quarter_end) for its fiscal quarter.\"\"\"\n fiscal_year = d.year if d.month >= fiscal_start_month else d.year - 1\n q = ((d.month - fiscal_start_month) % 12) // 3 + 1\n sy, sm = fiscal_year, fiscal_start_month + (q - 1) * 3\n while sm > 12:\n sm -= 12\n sy += 1\n start = date(sy, sm, 1)\n ey, em = sy, sm + 2\n if em > 12:\n em -= 12\n ey += 1\n end = month_end(ey, em)\n label = \"FY{}-Q{}\".format(fiscal_year, q)\n return label, start, end\n\n\ndef next_quarter_start(start, months=3):\n \"\"\"Return the first day of the fiscal quarter following the one starting at `start`.\"\"\"\n m = start.month - 1 + months\n y = start.year + m // 12\n m = m % 12 + 1\n return date(y, m, 1)\n\n\ndef quarterly_report(entries, fiscal_start_month=4):\n \"\"\"Build a per-fiscal-quarter bookkeeping report from raw ledger entries.\"\"\"\n if not entries:\n return []\n\n parsed = []\n for date_str, debit, credit in entries:\n y, m, d = map(int, date_str.split(\"-\"))\n parsed.append((date(y, m, d), Decimal(debit), Decimal(credit)))\n parsed.sort(key=lambda t: t[0])\n\n # Combine all entries that share the same date into a single net event.\n combined = {}\n for d, debit, credit in parsed:\n acc = combined.setdefault(d, [Decimal(\"0.00\"), Decimal(\"0.00\")])\n acc[0] += debit\n acc[1] += credit\n events = sorted(combined.items())\n\n label, start, end = quarter_bounds(events[0][0], fiscal_start_month)\n _, last_start, _ = quarter_bounds(events[-1][0], fiscal_start_month)\n\n results = []\n idx = 0\n opening = Decimal(\"0.00\")\n\n while start <= last_start:\n # Fold any entries dated before this quarter into the opening balance.\n while idx < len(events) and events[idx][0] < start:\n debit, credit = events[idx][1]\n opening += debit - credit\n idx += 1\n\n balance = opening\n debits = Decimal(\"0.00\")\n credits = Decimal(\"0.00\")\n weighted_sum = Decimal(\"0.00\")\n cursor = start\n\n # Walk through this quarter's events, weighting each balance by days held.\n while idx < len(events) and events[idx][0] <= end:\n event_date, (debit, credit) = events[idx]\n days = (event_date - cursor).days\n if days:\n weighted_sum += balance * days\n balance += debit - credit\n debits += debit\n credits += credit\n cursor = event_date\n idx += 1\n\n # The final balance holds from the last event through quarter end, inclusive.\n weighted_sum += balance * ((end - cursor).days + 1)\n total_days = (end - start).days + 1\n average = money(weighted_sum / total_days)\n\n results.append({\n \"quarter\": label,\n \"start\": start.isoformat(),\n \"end\": end.isoformat(),\n \"opening_balance\": money(opening),\n \"total_debits\": money(debits),\n \"total_credits\": money(credits),\n \"closing_balance\": money(balance),\n \"average_daily_balance\": average,\n })\n\n opening = balance\n start = next_quarter_start(start)\n label, start, end = quarter_bounds(start, fiscal_start_month)\n\n return results\n\n\nif __name__ == \"__main__\":\n entries = [\n (\"2025-04-01\", \"1000.00\", \"0.00\"),\n (\"2025-05-15\", \"0.00\", \"250.50\"),\n (\"2025-06-30\", \"100.00\", \"0.00\"),\n (\"2025-07-10\", \"300.00\", \"0.00\"),\n ]\n report = quarterly_report(entries, fiscal_start_month=4)\n\n q1, q2 = report\n assert q1[\"quarter\"] == \"FY2025-Q1\"\n assert q1[\"start\"] == \"2025-04-01\" and q1[\"end\"] == \"2025-06-30\"\n assert q1[\"opening_balance\"] == Decimal(\"0.00\")\n assert q1[\"total_debits\"] == Decimal(\"1100.00\")\n assert q1[\"total_credits\"] == Decimal(\"250.50\")\n assert q1[\"closing_balance\"] == Decimal(\"849.50\")\n assert q1[\"average_daily_balance\"] == Decimal(\"871.72\")\n\n assert q2[\"quarter\"] == \"FY2025-Q2\"\n assert q2[\"start\"] == \"2025-07-01\" and q2[\"end\"] == \"2025-09-30\"\n assert q2[\"opening_balance\"] == Decimal(\"849.50\")\n assert q2[\"total_debits\"] == Decimal(\"300.00\")\n assert q2[\"total_credits\"] == Decimal(\"0.00\")\n assert q2[\"closing_balance\"] == Decimal(\"1149.50\")\n assert q2[\"average_daily_balance\"] == Decimal(\"1120.15\")\n\n # A January entry belongs to FY2025-Q4 (quarter ending 2026-03-31).\n jan_report = quarterly_report([(\"2026-01-15\", \"10.00\", \"0.00\")], 4)\n assert jan_report[0][\"quarter\"] == \"FY2025-Q4\"\n assert jan_report[0][\"end\"] == \"2026-03-31\"\n\n for row in report:\n print(row)\n print(\"All checks passed.\")"}], "meta": {"idx": 2309, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1785, "latency_s": 142.4}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, useful_life, method, rate=None)` that builds a depreciation schedule for a fixed asset using either the straight-line method ('straight_line') or the declining-balance method ('declining_balance'). Use `decimal.Decimal` for all monetary math and round each depreciation expense to 2 decimal places with ROUND_HALF_UP. For straight-line, the annual expense is (cost - salvage) / useful_life, applied each year, with a final-year plug so the accumulated depreciation ends exactly at cost - salvage. For declining-balance, the annual expense is beginning book value * rate (rate is a Decimal like Decimal('0.40') for 40%), but the expense must never push book value below salvage; in the year it would, take only the remaining amount (book value - salvage) and stop. Return a list of dictionaries, one per year, with keys 'year' (int, starting at 1), 'expense' (Decimal), 'accumulated' (Decimal), and 'book_value' (Decimal, the end-of-year value). Example: cost=Decimal('10000.00'), salvage=Decimal('1000.00'), useful_life=5, method='straight_line' gives expenses [1800.00, 1800.00, 1800.00, 1800.00, 1800.00] and final book_value Decimal('1000.00'). Example: cost=Decimal('10000.00'), salvage=Decimal('1000.00'), method='declining_balance', rate=Decimal('0.40') gives year 1 expense Decimal('4000.00'), year 2 expense Decimal('2400.00'), year 3 expense Decimal('1440.00'), year 4 expense Decimal('864.00') (book value would drop below salvage, so capped), and final book_value Decimal('1000.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef depreciation_schedule(cost, salvage, useful_life, method, rate=None):\n cost = Decimal(cost)\n salvage = Decimal(salvage)\n two = Decimal('0.01')\n\n schedule = []\n book_value = cost\n accumulated = Decimal('0.00')\n\n if method == 'straight_line':\n total = cost - salvage\n base = (total / Decimal(useful_life)).quantize(two, rounding=ROUND_HALF_UP)\n for year in range(1, useful_life + 1):\n if year < useful_life:\n expense = base\n else:\n expense = (total - accumulated).quantize(two, rounding=ROUND_HALF_UP)\n accumulated += expense\n book_value = cost - accumulated\n schedule.append({\n 'year': year,\n 'expense': expense.quantize(two, rounding=ROUND_HALF_UP),\n 'accumulated': accumulated.quantize(two, rounding=ROUND_HALF_UP),\n 'book_value': book_value.quantize(two, rounding=ROUND_HALF_UP),\n })\n elif method == 'declining_balance':\n if rate is None:\n raise ValueError(\"rate is required for declining_balance\")\n rate = Decimal(rate)\n year = 1\n while book_value > salvage:\n raw = (book_value * rate).quantize(two, rounding=ROUND_HALF_UP)\n expense = min(raw, book_value - salvage)\n expense = expense.quantize(two, rounding=ROUND_HALF_UP)\n accumulated += expense\n book_value = cost - accumulated\n schedule.append({\n 'year': year,\n 'expense': expense,\n 'accumulated': accumulated.quantize(two, rounding=ROUND_HALF_UP),\n 'book_value': book_value.quantize(two, rounding=ROUND_HALF_UP),\n })\n if book_value <= salvage:\n break\n year += 1\n else:\n raise ValueError(\"method must be 'straight_line' or 'declining_balance'\")\n\n return schedule\n\n\nif __name__ == '__main__':\n sl = depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5, 'straight_line')\n assert [row['expense'] for row in sl] == [Decimal('1800.00')] * 5\n assert sl[-1]['book_value'] == Decimal('1000.00')\n\n db = depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5, 'declining_balance', rate=Decimal('0.40'))\n assert [row['expense'] for row in db] == [Decimal('4000.00'), Decimal('2400.00'), Decimal('1440.00'), Decimal('864.00')]\n assert db[-1]['book_value'] == Decimal('1000.00')\n print('All checks passed.')"}], "meta": {"idx": 2350, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 1055, "latency_s": 9.8}} +{"prompt": [{"role": "user", "content": "You are keeping the books for a fixed-payment, declining-balance loan. Given a loan principal, an annual nominal interest rate (interest accrues monthly as balance * rate/12, rounded to the nearest cent with ROUND_HALF_UP), and a level monthly payment, produce the full amortization ledger. Each monthly entry must record: entry number, opening balance, interest accrued (rounded to cents), principal repaid, payment made, and closing balance; the principal portion is payment minus interest, capped at the outstanding balance, and the final payment is adjusted downward so the closing balance is exactly zero. All arithmetic must use Decimal (never float), and after building the ledger you must validate it: every payment equals interest plus principal, every closing balance equals opening balance minus principal, the first opening balance equals the principal, the last closing balance is zero, and total paid equals total interest plus total principal. If the payment does not exceed the first month's interest, raise ValueError. Worked example: principal 10000.00, annual rate 6% (0.06), monthly payment 500.00. Entry 1: opening 10000.00, interest 50.00, principal 450.00, payment 500.00, closing 9550.00. Entry 2: opening 9550.00, interest 47.75, principal 452.25, payment 500.00, closing 9097.75. The ledger has 22 entries; the final entry has opening balance 62.21, interest 0.31, principal 62.21, payment 62.52, closing 0.00; total interest is 562.52 and total paid is 10562.52."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\ndef to_money(value):\n \"\"\"Round a Decimal to cents using ROUND_HALF_UP.\"\"\"\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef build_amortization_ledger(principal, annual_rate, monthly_payment):\n \"\"\"Build and validate a fixed-payment declining-balance loan ledger.\n\n Returns a dict with 'entries' (list of per-month dicts) and 'totals'.\n Raises ValueError for invalid inputs or a payment that never amortizes\n the loan.\n \"\"\"\n principal = Decimal(str(principal))\n annual_rate = Decimal(str(annual_rate))\n monthly_payment = Decimal(str(monthly_payment))\n\n if principal <= 0:\n raise ValueError(\"principal must be positive\")\n if annual_rate < 0:\n raise ValueError(\"annual rate cannot be negative\")\n if monthly_payment <= 0:\n raise ValueError(\"monthly payment must be positive\")\n\n monthly_rate = annual_rate / Decimal(12)\n first_interest = to_money(principal * monthly_rate)\n if monthly_payment <= first_interest:\n raise ValueError(\n \"monthly payment does not exceed the first month's interest; \"\n \"the loan will never be repaid\"\n )\n\n entries = []\n balance = to_money(principal)\n month = 0\n MAX_MONTHS = 1200 # safety guard against runaway loops\n\n while balance > ZERO:\n month += 1\n if month > MAX_MONTHS:\n raise ValueError(\"ledger exceeded maximum number of entries\")\n\n opening = balance\n interest = to_money(opening * monthly_rate)\n principal_part = monthly_payment - interest\n\n if principal_part >= opening:\n # Final entry: pay off exactly the remaining balance.\n principal_part = opening\n payment = interest + principal_part\n else:\n payment = monthly_payment\n\n closing = opening - principal_part\n\n entries.append(\n {\n \"entry\": month,\n \"opening_balance\": opening,\n \"interest\": interest,\n \"principal\": principal_part,\n \"payment\": payment,\n \"closing_balance\": closing,\n }\n )\n balance = closing\n\n total_interest = sum((e[\"interest\"] for e in entries), ZERO)\n total_principal = sum((e[\"principal\"] for e in entries), ZERO)\n total_paid = sum((e[\"payment\"] for e in entries), ZERO)\n\n ledger = {\n \"entries\": entries,\n \"totals\": {\n \"entries\": len(entries),\n \"total_interest\": total_interest,\n \"total_principal\": total_principal,\n \"total_paid\": total_paid,\n },\n }\n\n _validate_ledger(ledger, principal)\n return ledger\n\n\ndef _validate_ledger(ledger, principal):\n \"\"\"Check all bookkeeping invariants; raise ValueError on any breach.\"\"\"\n entries = ledger[\"entries\"]\n totals = ledger[\"totals\"]\n\n if not entries:\n raise ValueError(\"ledger has no entries\")\n\n if entries[0][\"opening_balance\"] != to_money(principal):\n raise ValueError(\"first opening balance does not equal the principal\")\n\n if entries[-1][\"closing_balance\"] != ZERO:\n raise ValueError(\"last closing balance is not zero\")\n\n for e in entries:\n if e[\"payment\"] != e[\"interest\"] + e[\"principal\"]:\n raise ValueError(\n \"entry %d: payment does not equal interest plus principal\" % e[\"entry\"]\n )\n if e[\"closing_balance\"] != e[\"opening_balance\"] - e[\"principal\"]:\n raise ValueError(\n \"entry %d: closing balance does not equal opening minus principal\"\n % e[\"entry\"]\n )\n if e[\"principal\"] <= ZERO:\n raise ValueError(\"entry %d: non-positive principal repayment\" % e[\"entry\"])\n\n for prev, cur in zip(entries, entries[1:]):\n if cur[\"opening_balance\"] != prev[\"closing_balance\"]:\n raise ValueError(\n \"entry %d: opening balance does not chain from previous entry\"\n % cur[\"entry\"]\n )\n\n if totals[\"total_interest\"] != sum((e[\"interest\"] for e in entries), ZERO):\n raise ValueError(\"total interest mismatch\")\n if totals[\"total_principal\"] != sum((e[\"principal\"] for e in entries), ZERO):\n raise ValueError(\"total principal mismatch\")\n if totals[\"total_paid\"] != sum((e[\"payment\"] for e in entries), ZERO):\n raise ValueError(\"total paid mismatch\")\n if totals[\"total_paid\"] != totals[\"total_interest\"] + totals[\"total_principal\"]:\n raise ValueError(\"total paid does not equal interest plus principal\")\n if totals[\"total_principal\"] != to_money(principal):\n raise ValueError(\"total principal repaid does not equal the loan principal\")\n if totals[\"entries\"] != len(entries):\n raise ValueError(\"entry count mismatch\")\n\n\nif __name__ == \"__main__\":\n ledger = build_amortization_ledger(\"10000.00\", \"0.06\", \"500.00\")\n\n header = (\n \"{:>5} {:>12} {:>10} {:>10} {:>10} {:>12}\".format(\n \"No.\", \"Opening\", \"Interest\", \"Principal\", \"Payment\", \"Closing\"\n )\n )\n print(header)\n print(\"-\" * len(header))\n for e in ledger[\"entries\"]:\n print(\n \"{entry:>5} {opening_balance:>12} {interest:>10} {principal:>10} \"\n \"{payment:>10} {closing_balance:>12}\".format(**e)\n )\n\n t = ledger[\"totals\"]\n print(\"-\" * len(header))\n print(\n \"Entries: {entries} Total interest: {total_interest} \"\n \"Total principal: {total_principal} Total paid: {total_paid}\".format(**t)\n )"}], "meta": {"idx": 2337, "topic": "interest calculation and payment schedules", "difficulty": "hard", "provider": "novita", "in_tokens": 197, "out_tokens": 3887, "latency_s": 39.8}} +{"prompt": [{"role": "user", "content": "A small business keeps its ledger in USD but pays some invoices in EUR. Write a function `fx_gain_loss(entries, eur_usd_rates)` that computes the realized FX gain or loss for each EUR payment. `entries` is a list of tuples `(invoice_id, amount_eur, payment_eur, rate_at_invoice)` where `amount_eur` is the original invoice amount in EUR recorded at `rate_at_invoice` (USD per EUR), and `payment_eur` is the EUR amount actually paid. `eur_usd_rates` is a dict mapping payment date string to the USD-per-EUR rate on that date; each entry is settled on the date whose key equals `invoice_id`. The USD value recorded at invoice time is `amount_eur * rate_at_invoice`, and the USD value paid is `payment_eur * rate_on_payment_date`, both rounded to 2 decimal places with ROUND_HALF_UP. For each entry, return the realized FX gain/loss in USD as `paid_usd - recorded_usd` (positive = gain, negative = loss), rounded to 2 decimal places. The function returns a list of these values in the same order as the entries. Example: entries = [('2024-01-15', Decimal('100'), Decimal('100'), Decimal('1.10'))], eur_usd_rates = {'2024-01-15': Decimal('1.05')} gives [Decimal('-5.00')] because recorded_usd = 110.00 and paid_usd = 105.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef fx_gain_loss(entries, eur_usd_rates):\n results = []\n for invoice_id, amount_eur, payment_eur, rate_at_invoice in entries:\n recorded_usd = (Decimal(amount_eur) * Decimal(rate_at_invoice)).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP\n )\n payment_rate = Decimal(eur_usd_rates[invoice_id])\n paid_usd = (Decimal(payment_eur) * payment_rate).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP\n )\n results.append((paid_usd - recorded_usd).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP\n ))\n return results\n\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-15', Decimal('100'), Decimal('100'), Decimal('1.10')),\n ('2024-02-01', Decimal('250'), Decimal('250'), Decimal('1.08')),\n ('2024-03-10', Decimal('80'), Decimal('79'), Decimal('1.12')),\n ]\n rates = {\n '2024-01-15': Decimal('1.05'),\n '2024-02-01': Decimal('1.09'),\n '2024-03-10': Decimal('1.12'),\n }\n print(fx_gain_loss(entries, rates))"}], "meta": {"idx": 2352, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 596, "latency_s": 6.2}} +{"prompt": [{"role": "user", "content": "Implement an accounting system using dataclasses to represent ledger entries and produce a trial balance report. Each entry has a date (ISO string), account name, debit amount, and credit amount; amounts must be stored as Decimal rounded to 2 places with ROUND_HALF_UP. Create a class Ledger with methods add_entry(date, account, debit, credit) and trial_balance(), which returns a dict mapping each account to its net balance (debits minus credits) as a Decimal rounded to 2 places. If any entry has a negative debit or credit, raise ValueError. The ledger must also validate that total debits equal total credits via a method is_balanced(), returning True or False. Example: adding ('2024-01-01', 'Cash', '100.005', '0') and ('2024-01-01', 'Revenue', '0', '100.00') yields trial_balance {'Cash': Decimal('100.01'), 'Revenue': Decimal('-100.00')} and is_balanced() is False (since 100.01 != 100.00)."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Dict\n\nTWO = Decimal('0.01')\n\ndef to_money(value) -> Decimal:\n return Decimal(str(value)).quantize(TWO, rounding=ROUND_HALF_UP)\n\n@dataclass\nclass Entry:\n date: str\n account: str\n debit: Decimal\n credit: Decimal\n\n def __post_init__(self):\n self.debit = to_money(self.debit)\n self.credit = to_money(self.credit)\n if self.debit < 0 or self.credit < 0:\n raise ValueError('debit and credit must be non-negative')\n\nclass Ledger:\n def __init__(self):\n self.entries = []\n\n def add_entry(self, date: str, account: str, debit, credit):\n self.entries.append(Entry(date, account, debit, credit))\n\n def trial_balance(self) -> Dict[str, Decimal]:\n balances: Dict[str, Decimal] = {}\n for e in self.entries:\n balances[e.account] = balances.get(e.account, Decimal('0.00')) + e.debit - e.credit\n return {acc: bal.quantize(TWO, rounding=ROUND_HALF_UP) for acc, bal in balances.items()}\n\n def is_balanced(self) -> bool:\n total_debits = sum((e.debit for e in self.entries), Decimal('0.00'))\n total_credits = sum((e.credit for e in self.entries), Decimal('0.00'))\n return total_debits == total_credits\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add_entry('2024-01-01', 'Cash', '100.005', '0')\n ledger.add_entry('2024-01-01', 'Revenue', '0', '100.00')\n print(ledger.trial_balance())\n print(ledger.is_balanced())\n assert ledger.trial_balance() == {'Cash': Decimal('100.01'), 'Revenue': Decimal('-100.00')}\n assert ledger.is_balanced() is False"}], "meta": {"idx": 2349, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 665, "latency_s": 27.6}} +{"prompt": [{"role": "user", "content": "At period-end, a bookkeeper must post closing entries to zero out the temporary (nominal) accounts and transfer their net balances to the Retained Earnings account. You are given a list of ledger accounts, each with a name, a type (one of 'revenue', 'expense', or 'permanent'), and a trial-balance amount (positive = debit balance, negative = credit balance, as an integer number of cents). Write a function `post_closing_entries(accounts)` that returns a tuple `(closing_entries, retained_earnings_delta)` where `closing_entries` is a list of tuples `(account_name, debit, credit)` in the order the accounts appear in the input, and `retained_earnings_delta` is the net amount posted to Retained Earnings as an integer number of cents. For each revenue account (credit balance, negative amount), post a debit to close it; for each expense account (debit balance, positive amount), post a credit to close it; permanent accounts get no closing entry. Use `Decimal` with ROUND_HALF_UP for any division/rounding if needed, though with integer cents all results should be exact. For example, input [('Sales Revenue','revenue',-50000), ('Rent Expense','expense',12000), ('Salaries Expense','expense',30000), ('Cash','permanent',8000)] should return ([('Sales Revenue', 50000, 0), ('Rent Expense', 0, 12000), ('Salaries Expense', 0, 30000)], 8000), because revenues of 50000 minus expenses of 42000 leaves 8000 cents credited to Retained Earnings. An account with a zero balance should produce no closing entry."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef post_closing_entries(accounts):\n \"\"\"Post period-end closing entries for temporary accounts.\n\n Args:\n accounts: list of (name, type, balance_cents) tuples, where a positive\n balance is a debit and a negative balance is a credit.\n\n Returns:\n (closing_entries, retained_earnings_delta) where closing_entries is a\n list of (account_name, debit_cents, credit_cents) and\n retained_earnings_delta is the net credit (positive) or debit\n (negative) posted to Retained Earnings, in cents.\n \"\"\"\n closing_entries = []\n net_income_cents = 0\n\n for name, acct_type, balance in accounts:\n if acct_type not in ('revenue', 'expense', 'permanent'):\n raise ValueError(\"Account type must be 'revenue', 'expense', or 'permanent'\")\n if not isinstance(balance, int):\n raise TypeError('Balances must be integer cents')\n\n if acct_type == 'permanent' or balance == 0:\n continue\n\n if acct_type == 'revenue':\n if balance < 0:\n # Credit balance: debit to close it.\n closing_entries.append((name, -balance, 0))\n net_income_cents += -balance\n else:\n # Debit-balance revenue (e.g., sales returns): credit to close.\n closing_entries.append((name, 0, balance))\n net_income_cents -= balance\n elif acct_type == 'expense':\n if balance > 0:\n # Debit balance: credit to close it.\n closing_entries.append((name, 0, balance))\n net_income_cents -= balance\n else:\n # Credit-balance expense (e.g., refund): debit to close.\n closing_entries.append((name, -balance, 0))\n net_income_cents += -balance\n\n # Round via Decimal (exact for integers, but kept for specification compliance).\n delta = Decimal(net_income_cents).quantize(Decimal('1'), rounding=ROUND_HALF_UP)\n return closing_entries, int(delta)\n\n\nif __name__ == '__main__':\n accounts = [\n ('Sales Revenue', 'revenue', -50000),\n ('Rent Expense', 'expense', 12000),\n ('Salaries Expense', 'expense', 30000),\n ('Cash', 'permanent', 8000),\n ]\n entries, delta = post_closing_entries(accounts)\n assert entries == [\n ('Sales Revenue', 50000, 0),\n ('Rent Expense', 0, 12000),\n ('Salaries Expense', 0, 30000),\n ], entries\n assert delta == 8000, delta\n print(entries, delta)\n\n # Zero-balance accounts produce no entries.\n entries2, delta2 = post_closing_entries([('Fees Earned', 'revenue', 0),\n ('Utilities', 'expense', 0)])\n assert entries2 == [] and delta2 == 0\n print(entries2, delta2)"}], "meta": {"idx": 2317, "topic": "period-end closing entries and routines", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1112, "latency_s": 141.5}} +{"prompt": [{"role": "user", "content": "Implement a double-entry ledger using dataclasses and Decimal arithmetic. Define a `LedgerEntry` dataclass with fields `date` (str, ISO format), `description` (str), and `postings` (tuple of (account: str, amount: Decimal) pairs), where a valid entry's postings must sum to exactly zero. Implement a `Ledger` class that stores entries and provides: `add_entry(entry)` which raises `ValueError` if the entry does not balance (use `Decimal('0.00')` comparison after quantizing each amount to cents with ROUND_HALF_UP); `balance(account)` returning the net balance of an account as a Decimal quantized to cents; and `trial_balance()` returning a dict mapping each account to its balance. Amounts may be negative (debits negative, credits positive or vice versa). Example: entry with postings (('cash', Decimal('100.00')), ('revenue', Decimal('-100.00'))) balances; adding ('cash', Decimal('50.00')), ('revenue', Decimal('-49.99')) must raise ValueError. After adding the balanced entry, `balance('cash')` returns Decimal('100.00') and `trial_balance()` returns {'cash': Decimal('100.00'), 'revenue': Decimal('-100.00')}."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Tuple\n\nCENT = Decimal('0.01')\n\n\ndef to_cents(value: Decimal) -> Decimal:\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\n@dataclass(frozen=True)\nclass LedgerEntry:\n date: str\n description: str\n postings: Tuple[Tuple[str, Decimal], ...]\n\n def is_balanced(self) -> bool:\n total = sum((to_cents(amount) for _, amount in self.postings), Decimal('0.00'))\n return total == Decimal('0.00')\n\n\nclass Ledger:\n def __init__(self):\n self.entries = []\n\n def add_entry(self, entry: LedgerEntry) -> None:\n if not isinstance(entry, LedgerEntry):\n raise TypeError('entry must be a LedgerEntry')\n if not entry.is_balanced():\n raise ValueError(f'entry does not balance: {entry.description}')\n self.entries.append(entry)\n\n def balance(self, account: str) -> Decimal:\n total = Decimal('0.00')\n for entry in self.entries:\n for acct, amount in entry.postings:\n if acct == account:\n total += to_cents(amount)\n return total.quantize(CENT, rounding=ROUND_HALF_UP)\n\n def trial_balance(self) -> dict:\n result = {}\n for entry in self.entries:\n for acct, amount in entry.postings:\n result[acct] = result.get(acct, Decimal('0.00')) + to_cents(amount)\n return {acct: bal.quantize(CENT, rounding=ROUND_HALF_UP)\n for acct, bal in result.items()}\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n good = LedgerEntry('2024-01-15', 'Sale', (\n ('cash', Decimal('100.00')),\n ('revenue', Decimal('-100.00')),\n ))\n ledger.add_entry(good)\n bad = LedgerEntry('2024-01-16', 'Bad entry', (\n ('cash', Decimal('50.00')),\n ('revenue', Decimal('-49.99')),\n ))\n try:\n ledger.add_entry(bad)\n raise AssertionError('expected ValueError')\n except ValueError:\n pass\n assert ledger.balance('cash') == Decimal('100.00')\n assert ledger.trial_balance() == {\n 'cash': Decimal('100.00'),\n 'revenue': Decimal('-100.00'),\n }\n print('All checks passed.')"}], "meta": {"idx": 2356, "topic": "accounting record dataclasses and schemas", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 863, "latency_s": 7.6}} +{"prompt": [{"role": "user", "content": "You are given a CSV file of bank transactions with columns: date,description,amount. Amounts may be strings like '12.50', '-3.75', or '+100.00'. Write a function `process_transactions(csv_text)` that parses the CSV text, validates each row, and returns a summary. Validation rules: a row is valid if the date matches YYYY-MM-DD and is a real calendar date, the description is a non-empty string, and the amount parses as a Decimal with at most 2 decimal places. Invalid rows should be skipped (not raise). The returned summary must be a dict with keys: 'valid_count', 'invalid_count', 'total_debits' (sum of positive amounts, as a Decimal rounded to 2 places with ROUND_HALF_UP), 'total_credits' (sum of negative amounts, returned as a positive Decimal rounded to 2 places), and 'balance' (total_debits minus total_credits, rounded to 2 places). Use the decimal module for all monetary arithmetic. Example: input text 'date,description,amount\\n2024-01-15,Grocery store,45.20\\n2024-01-16,Refund,-10.00\\n2024-13-01,Bad date,5.00\\n2024-01-17,Coffee,3.25\\n' yields {'valid_count': 3, 'invalid_count': 1, 'total_debits': Decimal('48.45'), 'total_credits': Decimal('10.00'), 'balance': Decimal('38.45')}. Note: 45.20 + 3.25 = 48.45, and the refund of -10.00 counts as a 10.00 credit."}], "completion": [{"role": "assistant", "content": "import csv\nimport io\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom datetime import datetime\n\n\ndef process_transactions(csv_text):\n TWO = Decimal('0.01')\n\n def round2(d):\n return d.quantize(TWO, rounding=ROUND_HALF_UP)\n\n def valid_date(s):\n try:\n datetime.strptime(s, '%Y-%m-%d')\n return True\n except ValueError:\n return False\n\n def valid_amount(s):\n try:\n d = Decimal(s)\n except Exception:\n return None\n if d.as_tuple().exponent < -2:\n return None\n return d\n\n valid_count = 0\n invalid_count = 0\n debits = Decimal('0')\n credits = Decimal('0')\n\n reader = csv.DictReader(io.StringIO(csv_text))\n for row in reader:\n date = (row.get('date') or '').strip()\n desc = (row.get('description') or '').strip()\n amount_str = (row.get('amount') or '').strip()\n\n amount = valid_amount(amount_str)\n if not valid_date(date) or not desc or amount is None:\n invalid_count += 1\n continue\n\n valid_count += 1\n if amount >= 0:\n debits += amount\n else:\n credits += -amount\n\n total_debits = round2(debits)\n total_credits = round2(credits)\n balance = round2(debits - credits)\n\n return {\n 'valid_count': valid_count,\n 'invalid_count': invalid_count,\n 'total_debits': total_debits,\n 'total_credits': total_credits,\n 'balance': balance,\n }\n\n\nif __name__ == '__main__':\n sample = 'date,description,amount\\n2024-01-15,Grocery store,45.20\\n2024-01-16,Refund,-10.00\\n2024-13-01,Bad date,5.00\\n2024-01-17,Coffee,3.25\\n'\n print(process_transactions(sample))"}], "meta": {"idx": 2355, "topic": "transaction CSV import, validation, and export", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 777, "latency_s": 13.6}} +{"prompt": [{"role": "user", "content": "You are maintaining a simple accounting ledger. Define a dataclass `LedgerEntry` with fields `date` (string, ISO format YYYY-MM-DD), `description` (string), and `amount` (Decimal, positive for debit, negative for credit). Implement a function `validate_entries(entries)` that raises `ValueError` if any entry has a zero amount or an invalid date (must parse with `datetime.date.fromisoformat`). Implement `sum_balance(entries)` that returns the balance as a Decimal, rounded to 2 decimal places with ROUND_HALF_UP. Finally, implement `ledger_summary(entries)` that returns a dict with keys 'total_debits', 'total_credits', and 'balance', where debits are the sum of positive amounts, credits are the absolute sum of negative amounts, and all values are Decimals rounded to 2 places with ROUND_HALF_UP. Example: entries with amounts Decimal('100.555'), Decimal('-40.004') give total_debits Decimal('100.56'), total_credits Decimal('40.00'), balance Decimal('60.55')."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\n\n@dataclass\nclass LedgerEntry:\n date: str\n description: str\n amount: Decimal\n\n\ndef validate_entries(entries):\n for e in entries:\n if not isinstance(e.amount, Decimal):\n raise ValueError(f\"amount must be Decimal: {e.amount!r}\")\n if e.amount == 0:\n raise ValueError(f\"amount must be non-zero: {e.amount}\")\n try:\n date.fromisoformat(e.date)\n except (TypeError, ValueError):\n raise ValueError(f\"invalid date: {e.date!r}\")\n\n\ndef _round2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef sum_balance(entries):\n validate_entries(entries)\n total = sum((e.amount for e in entries), Decimal('0'))\n return _round2(total)\n\n\ndef ledger_summary(entries):\n validate_entries(entries)\n debits = sum((e.amount for e in entries if e.amount > 0), Decimal('0'))\n credits = sum((-e.amount for e in entries if e.amount < 0), Decimal('0'))\n return {\n 'total_debits': _round2(debits),\n 'total_credits': _round2(credits),\n 'balance': _round2(debits - credits),\n }\n\n\nif __name__ == '__main__':\n entries = [\n LedgerEntry('2024-01-15', 'Cash sale', Decimal('100.555')),\n LedgerEntry('2024-01-16', 'Supplier payment', Decimal('-40.004')),\n ]\n summary = ledger_summary(entries)\n assert summary['total_debits'] == Decimal('100.56')\n assert summary['total_credits'] == Decimal('40.00')\n assert summary['balance'] == Decimal('60.55')\n assert sum_balance(entries) == Decimal('60.55')\n print(summary)"}], "meta": {"idx": 2353, "topic": "accounting record dataclasses and schemas", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 681, "latency_s": 29.4}} +{"prompt": [{"role": "user", "content": "A talent agency's settlement office processes invoices where a tiered commission is deducted, a tip is added, and the remainder is split among participants by percentage. Write a function `process_settlements(invoices)` where each invoice is a dict with keys: `id` (str), `gross` (Decimal), `tiers` (list of dicts with `limit` (Decimal or None for the top bracket) and `rate` (Decimal percent), given in ascending order with cumulative limits), `tip_rate` (Decimal percent), and `participants` (list of `(name, share_pct)` tuples whose percentages sum to exactly 100). Commission is computed marginally per bracket, with each bracket's marginal amount rounded half-up to cents before summing; `net = gross - commission`; `tip = round_half_up(net * tip_rate / 100)`; the distributable amount is `net + tip`. Each participant's share is the exact value `distributable * share_pct / 100`; floor every share to whole cents, then hand out the leftover pennies one at a time to participants in descending order of fractional remainder, breaking ties by participant name in ascending alphabetical order. Return a report dict with `invoices` (each containing id, gross, commission, net, tip, distributable, and allocations), `participant_totals` (sum per participant across all invoices, using `Decimal` cents), and `balanced` (True only if every invoice's allocations sum exactly to its distributable and the participant totals sum to the grand total of distributables). Use `Decimal` with half-up rounding throughout\u2014never floats. Worked example: invoice `I-001` with gross `1000.00`, tiers `[(500, 5%), (800, 8%), (None, 12%)]`, tip `15%`, and participants Alice 33.333%, Bob 33.333%, Carol 33.334% yields commission `73.00`, net `927.00`, tip `139.05`, distributable `1066.05`, and allocations Alice `355.35`, Bob `355.34`, Carol `355.36` (Carol gets the first leftover penny for the largest fractional remainder, Alice the second by name-order tie-break)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, ROUND_FLOOR\n\nCENT = Decimal(\"0.01\")\n\n\ndef round_cents(value):\n \"\"\"Round a Decimal to cents using banker-free half-up rounding.\"\"\"\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef to_whole_cents(value):\n \"\"\"Convert a Decimal dollar amount to an integer number of cents (floor).\"\"\"\n return int((value / CENT).to_integral_value(rounding=ROUND_FLOOR))\n\n\ndef compute_commission(gross, tiers):\n \"\"\"Marginal tiered commission; each bracket rounded half-up to cents.\"\"\"\n commission = Decimal(\"0.00\")\n prev_limit = Decimal(\"0\")\n for tier in tiers:\n limit = tier[\"limit\"]\n rate = tier[\"rate\"]\n upper = gross if limit is None else min(gross, limit)\n if upper <= prev_limit:\n continue\n bracket_amount = upper - prev_limit\n commission += round_cents(bracket_amount * rate / Decimal(\"100\"))\n prev_limit = upper\n if gross <= upper:\n break\n return commission\n\n\ndef allocate(distributable, participants):\n \"\"\"Split by percentage; leftover pennies by largest remainder, name tie-break.\"\"\"\n total_cents = to_whole_cents(distributable)\n base_cents = {}\n remainders = {}\n allocated = 0\n for name, pct in participants:\n exact_cents = (Decimal(total_cents) * pct) / Decimal(\"100\")\n floor_cents = int(exact_cents.to_integral_value(rounding=ROUND_FLOOR))\n base_cents[name] = floor_cents\n remainders[name] = exact_cents - floor_cents\n allocated += floor_cents\n leftover = total_cents - allocated\n if leftover > 0:\n order = sorted(participants, key=lambda p: (-remainders[p[0]], p[0]))\n for i in range(leftover):\n base_cents[order[i % len(order)][0]] += 1\n elif leftover < 0:\n raise ValueError(\"Share percentages must sum to exactly 100\")\n return {name: (Decimal(cents) * CENT).quantize(CENT) for name, cents in base_cents.items()}\n\n\ndef process_settlements(invoices):\n report_invoices = []\n participant_totals = {}\n grand_distributable = Decimal(\"0.00\")\n balanced = True\n for inv in invoices:\n gross = inv[\"gross\"].quantize(CENT)\n commission = compute_commission(gross, inv[\"tiers\"])\n net = (gross - commission).quantize(CENT)\n tip = round_cents(net * inv[\"tip_rate\"] / Decimal(\"100\"))\n distributable = (net + tip).quantize(CENT)\n allocations = allocate(distributable, inv[\"participants\"])\n alloc_sum = sum(allocations.values(), Decimal(\"0.00\"))\n if alloc_sum != distributable:\n balanced = False\n grand_distributable += distributable\n for name, amount in allocations.items():\n participant_totals[name] = participant_totals.get(name, Decimal(\"0.00\")) + amount\n report_invoices.append({\n \"id\": inv[\"id\"],\n \"gross\": gross,\n \"commission\": commission,\n \"net\": net,\n \"tip\": tip,\n \"distributable\": distributable,\n \"allocations\": allocations,\n })\n totals_sum = sum(participant_totals.values(), Decimal(\"0.00\"))\n if totals_sum != grand_distributable:\n balanced = False\n return {\n \"invoices\": report_invoices,\n \"participant_totals\": dict(sorted(participant_totals.items())),\n \"balanced\": balanced,\n }\n\n\ndef main():\n D = Decimal\n invoices = [\n {\n \"id\": \"I-001\",\n \"gross\": D(\"1000.00\"),\n \"tiers\": [\n {\"limit\": D(\"500\"), \"rate\": D(\"5\")},\n {\"limit\": D(\"800\"), \"rate\": D(\"8\")},\n {\"limit\": None, \"rate\": D(\"12\")},\n ],\n \"tip_rate\": D(\"15\"),\n \"participants\": [(\"Alice\", D(\"33.333\")), (\"Bob\", D(\"33.333\")), (\"Carol\", D(\"33.334\"))],\n },\n {\n \"id\": \"I-002\",\n \"gross\": D(\"1500.00\"),\n \"tiers\": [\n {\"limit\": D(\"500\"), \"rate\": D(\"5\")},\n {\"limit\": D(\"800\"), \"rate\": D(\"8\")},\n {\"limit\": None, \"rate\": D(\"12\")},\n ],\n \"tip_rate\": D(\"10\"),\n \"participants\": [(\"Dana\", D(\"50\")), (\"Eve\", D(\"25\")), (\"Frank\", D(\"25\"))],\n },\n ]\n report = process_settlements(invoices)\n for inv in report[\"invoices\"]:\n print(f\"Invoice {inv['id']}: gross={inv['gross']} commission={inv['commission']} \"\n f\"net={inv['net']} tip={inv['tip']} distributable={inv['distributable']}\")\n for name, amount in inv[\"allocations\"].items():\n print(f\" {name}: {amount}\")\n print(\"Participant totals:\")\n for name, total in report[\"participant_totals\"].items():\n print(f\" {name}: {total}\")\n print(\"Balanced:\", report[\"balanced\"])\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2351, "topic": "commission, tip, and percentage splits", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1778, "latency_s": 38.8}} +{"prompt": [{"role": "user", "content": "Implement a small `Ledger` class for double-entry bookkeeping with precise monetary handling, plus a test suite. The ledger stores entries as (description, debit_account, credit_account, amount) tuples, where each entry debits one account and credits another for the same amount. Amounts must be handled as `Decimal` rounded to 2 decimal places with `ROUND_HALF_UP` at insertion time. Implement `add_entry(description, debit, credit, amount)` which raises `ValueError` if the amount is not positive, and `balance(account)` which returns the net balance of an account: debits increase the balance and credits decrease it. Also implement `is_balanced()`, which returns True if the sum of all account balances equals exactly Decimal('0.00') (which should always hold for a valid double-entry ledger). For example, adding ('sale', 'Cash', 'Revenue', Decimal('10.005')) then ('buy', 'Expenses', 'Cash', Decimal('2.50')) gives balance('Cash') == Decimal('7.50') because 10.005 rounds to 10.00. Then write unit tests using `unittest` covering: rounding behavior, ValueError on non-positive amounts, correct balances for multiple entries, and that `is_balanced()` is True."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nimport unittest\n\n\nclass Ledger:\n def __init__(self):\n self.entries = []\n\n def add_entry(self, description, debit, credit, amount):\n amount = Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if amount <= 0:\n raise ValueError('amount must be positive')\n self.entries.append((description, debit, credit, amount))\n\n def balance(self, account):\n total = Decimal('0.00')\n for _, debit, credit, amount in self.entries:\n if debit == account:\n total += amount\n if credit == account:\n total -= amount\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n def is_balanced(self):\n accounts = set()\n for _, debit, credit, _ in self.entries:\n accounts.add(debit)\n accounts.add(credit)\n return sum((self.balance(a) for a in accounts), Decimal('0.00')) == Decimal('0.00')\n\n\nclass TestLedger(unittest.TestCase):\n def test_rounding_half_up(self):\n ledger = Ledger()\n ledger.add_entry('sale', 'Cash', 'Revenue', Decimal('10.005'))\n self.assertEqual(ledger.balance('Cash'), Decimal('10.00'))\n ledger.add_entry('fee', 'Cash', 'Revenue', Decimal('2.345'))\n self.assertEqual(ledger.balance('Cash'), Decimal('12.35'))\n\n def test_non_positive_raises(self):\n ledger = Ledger()\n for bad in (Decimal('0'), Decimal('-5.00'), Decimal('-0.01')):\n with self.assertRaises(ValueError):\n ledger.add_entry('bad', 'A', 'B', bad)\n\n def test_balances(self):\n ledger = Ledger()\n ledger.add_entry('sale', 'Cash', 'Revenue', Decimal('10.005'))\n ledger.add_entry('buy', 'Expenses', 'Cash', Decimal('2.50'))\n self.assertEqual(ledger.balance('Cash'), Decimal('7.50'))\n self.assertEqual(ledger.balance('Revenue'), Decimal('-10.00'))\n self.assertEqual(ledger.balance('Expenses'), Decimal('2.50'))\n\n def test_is_balanced(self):\n ledger = Ledger()\n ledger.add_entry('sale', 'Cash', 'Revenue', Decimal('99.99'))\n ledger.add_entry('rent', 'Expenses', 'Cash', Decimal('12.34'))\n ledger.add_entry('wages', 'Expenses', 'Cash', Decimal('50.00'))\n self.assertTrue(ledger.is_balanced())\n\n\nif __name__ == '__main__':\n unittest.main()"}], "meta": {"idx": 2357, "topic": "unit tests for accounting functions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 911, "latency_s": 6.6}} +{"prompt": [{"role": "user", "content": "You are given journal entries as a list of tuples (entry_id, [(account_code, debit, credit), ...]) where debit and credit are strings of monetary amounts in dollars; every amount must be quantized to cents using Decimal with ROUND_HALF_UP before any arithmetic. An entry is balanced only if its total debits exactly equal its total credits; unbalanced entries must be quarantined (not posted to the ledger) and each reported with its difference (total debits minus total credits, as a two-decimal string) and a boolean 'possible_transposition' that is True when the difference, expressed in whole absolute cents, is nonzero and divisible by 9 (the classic transposition-error signature). Post all balanced entries to a ledger, compute each account's net = total debits - total credits, and produce a trial balance listing accounts sorted by account code, each as [code, side, amount] where side is 'DR' if net > 0, 'CR' if net < 0, or 'ZERO' with amount '0.00' if net == 0, and amount is the absolute net balance as a two-decimal string. The function build_trial_balance(entries) must return a dict with keys 'trial_balance' (that sorted list), 'total_dr' and 'total_cr' (two-decimal strings holding the sum of all debit-side balances and the sum of all credit-side balances respectively), and 'quarantined' (a list of dicts with keys 'entry_id', 'difference', 'possible_transposition', in input order). For example, entries E1=[('1000','1500.00','0.00'),('4000','0.00','1500.00')], E2=[('1000','0.00','200.00'),('5000','270.00','0.00'),('4000','0.00','70.00')], E3=[('1010','91.20','0.00'),('4000','0.00','91.02')] must yield trial_balance [['1000','DR','1300.00'],['4000','CR','1570.00'],['5000','DR','270.00']], total_dr '1570.00', total_cr '1570.00', and quarantined [{'entry_id':'E3','difference':'0.18','possible_transposition': True}] (E3 is excluded because 91.20 != 91.02, and its 18-cent difference is divisible by 9). Use only the standard library and Decimal arithmetic throughout."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\ndef _money(value):\n \"\"\"Parse a monetary string/number and quantize to cents with ROUND_HALF_UP.\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef build_trial_balance(entries):\n \"\"\"Build a trial balance from journal entries, quarantining unbalanced ones.\n\n entries: iterable of (entry_id, [(account_code, debit, credit), ...])\n Returns a dict with 'trial_balance', 'total_dr', 'total_cr', 'quarantined'.\n \"\"\"\n ledger = {} # account_code -> (sum_of_debits, sum_of_credits)\n quarantined = []\n\n for entry_id, lines in entries:\n parsed = []\n debits = ZERO\n credits = ZERO\n for code, dr, cr in lines:\n d = _money(dr)\n c = _money(cr)\n parsed.append((code, d, c))\n debits += d\n credits += c\n\n if debits == credits:\n # Post the balanced entry to the ledger.\n for code, d, c in parsed:\n acc_dr, acc_cr = ledger.get(code, (ZERO, ZERO))\n ledger[code] = (acc_dr + d, acc_cr + c)\n else:\n # Quarantine the unbalanced entry and analyze the difference.\n diff = (debits - credits).quantize(CENT)\n cents = int((diff.copy_abs() * 100).quantize(Decimal(\"1\"),\n rounding=ROUND_HALF_UP))\n quarantined.append({\n \"entry_id\": entry_id,\n \"difference\": str(diff),\n \"possible_transposition\": cents != 0 and cents % 9 == 0,\n })\n\n trial_balance = []\n total_dr = ZERO\n total_cr = ZERO\n for code in sorted(ledger):\n dr_sum, cr_sum = ledger[code]\n net = (dr_sum - cr_sum).quantize(CENT)\n if net > 0:\n side = \"DR\"\n amount = net\n total_dr += amount\n elif net < 0:\n side = \"CR\"\n amount = -net\n total_cr += amount\n else:\n side = \"ZERO\"\n amount = ZERO\n trial_balance.append([code, side, str(amount.quantize(CENT))])\n\n return {\n \"trial_balance\": trial_balance,\n \"total_dr\": str(total_dr.quantize(CENT)),\n \"total_cr\": str(total_cr.quantize(CENT)),\n \"quarantined\": quarantined,\n }\n\n\nif __name__ == \"__main__\":\n entries = [\n (\"E1\", [(\"1000\", \"1500.00\", \"0.00\"),\n (\"4000\", \"0.00\", \"1500.00\")]),\n (\"E2\", [(\"1000\", \"0.00\", \"200.00\"),\n (\"5000\", \"270.00\", \"0.00\"),\n (\"4000\", \"0.00\", \"70.00\")]),\n (\"E3\", [(\"1010\", \"91.20\", \"0.00\"),\n (\"4000\", \"0.00\", \"91.02\")]),\n ]\n\n result = build_trial_balance(entries)\n print(result)\n\n expected = {\n \"trial_balance\": [[\"1000\", \"DR\", \"1300.00\"],\n [\"4000\", \"CR\", \"1570.00\"],\n [\"5000\", \"DR\", \"270.00\"]],\n \"total_dr\": \"1570.00\",\n \"total_cr\": \"1570.00\",\n \"quarantined\": [{\"entry_id\": \"E3\", \"difference\": \"0.18\",\n \"possible_transposition\": True}],\n }\n assert result == expected, result\n print(\"Example verified OK\")"}], "meta": {"idx": 2334, "topic": "trial balance construction and imbalance detection", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1372, "latency_s": 117.7}} +{"prompt": [{"role": "user", "content": "Implement a `JournalEntry` record for double-entry bookkeeping using a frozen dataclass. Each entry has a date (string 'YYYY-MM-DD'), a description (string), and a lines tuple of `(account, debit, credit)` pairs where debit and credit are `Decimal` amounts rounded to 2 places. The dataclass must validate in `__post_init__` that debits equal credits (raise `ValueError` otherwise), that amounts are non-negative, and that rounding is applied via `quantize(Decimal('0.01'), ROUND_HALF_UP)`. Add a `balance()` method returning a dict mapping each account to its net debit-minus-credit balance as a Decimal. Example: an entry with lines `[('cash', Decimal('100.00'), Decimal('0')), ('revenue', Decimal('0'), Decimal('100.00'))]` balances, has `balance() == {'cash': Decimal('100.00'), 'revenue': Decimal('-100.00')}`, and an entry with debits 100.00 and credits 99.99 must raise `ValueError`."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Tuple\n\nTWO = Decimal('0.01')\n\n@dataclass(frozen=True)\nclass JournalEntry:\n date: str\n description: str\n lines: Tuple[Tuple[str, Decimal, Decimal], ...] = field(default_factory=tuple)\n\n def __post_init__(self):\n rounded = []\n for account, debit, credit in self.lines:\n d = Decimal(debit).quantize(TWO, rounding=ROUND_HALF_UP)\n c = Decimal(credit).quantize(TWO, rounding=ROUND_HALF_UP)\n if d < 0 or c < 0:\n raise ValueError(f\"Negative amount for account {account!r}\")\n rounded.append((account, d, c))\n total_d = sum((l[1] for l in rounded), Decimal('0'))\n total_c = sum((l[2] for l in rounded), Decimal('0'))\n if total_d != total_c:\n raise ValueError(f\"Unbalanced entry: debits {total_d} != credits {total_c}\")\n object.__setattr__(self, 'lines', tuple(rounded))\n\n def balance(self):\n result = {}\n for account, debit, credit in self.lines:\n result[account] = result.get(account, Decimal('0')) + debit - credit\n return result\n\nif __name__ == '__main__':\n e = JournalEntry('2024-01-15', 'Sale for cash', (\n ('cash', Decimal('100.00'), Decimal('0')),\n ('revenue', Decimal('0'), Decimal('100.00')),\n ))\n assert e.balance() == {'cash': Decimal('100.00'), 'revenue': Decimal('-100.00')}\n try:\n JournalEntry('2024-01-15', 'bad', (\n ('cash', Decimal('100.00'), Decimal('0')),\n ('revenue', Decimal('0'), Decimal('99.99')),\n ))\n assert False\n except ValueError:\n pass\n print('all checks passed')"}], "meta": {"idx": 2359, "topic": "accounting record dataclasses and schemas", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 674, "latency_s": 5.9}} +{"prompt": [{"role": "user", "content": "You are building the categorization engine for a small-business bookkeeping system. Each expense line item has a description string, and you must assign it to the correct account from a chart of accounts using keyword rules. The chart of accounts is a list of (code, name, keywords) tuples, where keywords is a list of lowercase substrings; an item matches the first account whose keyword appears anywhere in the lowercased description. Items with no match go to account '9999 - Unclassified'. Given a list of line items as (description, amount_cents) tuples, produce a trial-balance-style report: for each account that received at least one item (sorted by account code), print the account code and name, the number of items, and the total amount formatted as dollars with exactly two decimal places (use Decimal to avoid float errors, rounding half-up to the nearest cent). Finally print the grand total across all accounts. Example: chart = [('1000','Office Supplies',['paper','ink','stapler']), ('2000','Travel',['flight','hotel','taxi'])], items = [('Ink cartridges for printer', 4550), ('Taxi to airport', 1875), ('Random purchase', 999)] should yield: 1000 Office Supplies: 1 items, $45.50; 2000 Travel: 1 items, $18.75; 9999 Unclassified: 1 items, $9.99; Grand total: $74.24. Write a function categorize_expenses(chart, items) that returns the report as a single string with one line per account plus the grand-total line."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import OrderedDict\n\ndef categorize_expenses(chart, items):\n D = Decimal\n totals = OrderedDict()\n counts = OrderedDict()\n names = {}\n for code, name, keywords in chart:\n names[code] = name\n for desc, cents in items:\n lower = desc.lower()\n matched = None\n for code, name, keywords in chart:\n if any(kw in lower for kw in keywords):\n matched = code\n break\n if matched is None:\n matched = '9999'\n names.setdefault('9999', 'Unclassified')\n totals[matched] = totals.get(matched, D('0')) + D(cents)\n counts[matched] = counts.get(matched, 0) + 1\n lines = []\n grand = D('0')\n for code in sorted(totals.keys()):\n amount = (totals[code] / D('100')).quantize(D('0.01'), rounding=ROUND_HALF_UP)\n grand += amount\n lines.append(\"{} {}: {} items, ${:.2f}\".format(code, names[code], counts[code], amount))\n lines.append(\"Grand total: ${:.2f}\".format(grand))\n return \"\\n\".join(lines)\n\nif __name__ == '__main__':\n chart = [('1000', 'Office Supplies', ['paper', 'ink', 'stapler']),\n ('2000', 'Travel', ['flight', 'hotel', 'taxi'])]\n items = [('Ink cartridges for printer', 4550),\n ('Taxi to airport', 1875),\n ('Random purchase', 999)]\n print(categorize_expenses(chart, items))"}], "meta": {"idx": 2360, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 738, "latency_s": 7.5}} +{"prompt": [{"role": "user", "content": "Write a function `build_trial_balance(entries)` that constructs a trial balance from a list of journal entries and detects imbalance. Each entry is a tuple `(account, debit, credit)` where `debit` and `credit` are strings representing monetary amounts (e.g. '100.00', '0', '12.5'); amounts must be parsed with `Decimal` and quantized to 2 decimal places with `ROUND_HALF_UP`. For each account, accumulate the net movement as `sum(debits) - sum(credits)` and produce a balance line: if net >= 0 the account has a debit balance of that amount, otherwise a credit balance of the negated amount. The function must return a tuple `(debit_total, credit_total, imbalanced_accounts)` where `debit_total` and `credit_total` are Decimals quantized to 2 places summing the debit-balance column and credit-balance column of the trial balance, and `imbalanced_accounts` is a sorted list of accounts whose net movement is exactly zero (i.e., they contribute to neither column). Additionally, the trial balance itself is out of balance if `debit_total != credit_total`; in that case raise `ValueError` with a message starting with 'Trial balance out of balance:'. Example: entries = [('Cash','150.00','0'), ('Revenue','0','150.00'), ('Suspense','10.00','0'), ('Suspense','0','10.00')] gives debit_total = Decimal('150.00'), credit_total = Decimal('150.00'), imbalanced_accounts = ['Suspense']."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef build_trial_balance(entries):\n \"\"\"Build a trial balance from journal entries and detect imbalance.\n\n Args:\n entries: iterable of (account, debit_str, credit_str) tuples.\n\n Returns:\n (debit_total, credit_total, imbalanced_accounts) where the totals are\n Decimals quantized to 2 decimal places.\n\n Raises:\n ValueError: if the trial balance columns do not match.\n \"\"\"\n TWO = Decimal('0.01')\n\n def parse(amount_str):\n value = Decimal(amount_str)\n if value < 0:\n raise ValueError('Negative amount not allowed: %s' % amount_str)\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n accounts = {}\n for account, debit_str, credit_str in entries:\n debit = parse(debit_str)\n credit = parse(credit_str)\n net = accounts.get(account, Decimal('0.00'))\n net += debit - credit\n accounts[account] = net.quantize(TWO, rounding=ROUND_HALF_UP)\n\n debit_total = Decimal('0.00')\n credit_total = Decimal('0.00')\n imbalanced_accounts = []\n for account, net in accounts.items():\n if net > 0:\n debit_total += net\n elif net < 0:\n credit_total += -net\n else:\n imbalanced_accounts.append(account)\n\n debit_total = debit_total.quantize(TWO, rounding=ROUND_HALF_UP)\n credit_total = credit_total.quantize(TWO, rounding=ROUND_HALF_UP)\n\n if debit_total != credit_total:\n raise ValueError(\n 'Trial balance out of balance: debits %s vs credits %s'\n % (debit_total, credit_total)\n )\n\n return (debit_total, credit_total, sorted(imbalanced_accounts))\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', '150.00', '0'),\n ('Revenue', '0', '150.00'),\n ('Suspense', '10.00', '0'),\n ('Suspense', '0', '10.00'),\n ]\n result = build_trial_balance(entries)\n assert result == (Decimal('150.00'), Decimal('150.00'), ['Suspense'])\n print(result)"}], "meta": {"idx": 2361, "topic": "trial balance construction and imbalance detection", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 876, "latency_s": 7.3}} +{"prompt": [{"role": "user", "content": "A small business keeps an immutable audit trail of ledger entries. Each entry is recorded once as a tuple (entry_id, description, amount) where amount is a Decimal string; positive amounts are debits and negative amounts are credits. Because entries are immutable, corrections are made by appending a new reversal entry with the negated amount rather than editing old ones. Write a function `net_balance(entries)` that takes a list of these tuples and returns the net balance rounded to 2 decimal places using ROUND_HALF_UP. Additionally, write a function `is_valid_trail(entries)` that returns True only if every entry_id is a unique integer and no entry was modified (i.e., all amounts are valid Decimal strings and each entry is a tuple of exactly 3 items). For example, entries = [(1, 'sale', '12.50'), (2, 'refund', '-4.255'), (3, 'reversal of refund', '4.255')] gives net_balance('12.50 - 4.255 + 4.255') = Decimal('12.50'), and is_valid_trail returns True since all IDs are unique and amounts are valid."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, InvalidOperation\n\n\ndef is_valid_trail(entries):\n seen_ids = set()\n for entry in entries:\n if not isinstance(entry, tuple) or len(entry) != 3:\n return False\n entry_id, _description, amount = entry\n if not isinstance(entry_id, int) or isinstance(entry_id, bool):\n return False\n if entry_id in seen_ids:\n return False\n seen_ids.add(entry_id)\n if not isinstance(amount, str):\n return False\n try:\n Decimal(amount)\n except InvalidOperation:\n return False\n return True\n\n\ndef net_balance(entries):\n total = Decimal('0')\n for _entry_id, _description, amount in entries:\n total += Decimal(amount)\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n entries = [\n (1, 'sale', '12.50'),\n (2, 'refund', '-4.255'),\n (3, 'reversal of refund', '4.255'),\n ]\n assert is_valid_trail(entries) is True\n assert net_balance(entries) == Decimal('12.50')\n bad = [(1, 'sale', '12.50'), (1, 'duplicate id', '3.00')]\n assert is_valid_trail(bad) is False\n assert net_balance([(1, 'fee', '0.005')]) == Decimal('0.01')\n print('All checks passed.')"}], "meta": {"idx": 2362, "topic": "audit trails and immutable entry logs", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 594, "latency_s": 7.6}} +{"prompt": [{"role": "user", "content": "You are maintaining a simple cash ledger for a small shop. Each transaction is given as a line with a transaction id, a type ('entry' for a normal transaction, 'reversal' which cancels a previous entry by id, or 'void' which cancels a previous entry by id and marks it voided), and a signed amount in cents (positive for money received, negative for money paid out). Reversed or voided entries must be excluded from the ledger balance, and each entry can be reversed or voided at most once; a reversal/void referencing an unknown id, an already-canceled entry, or another reversal/void is invalid and must be reported. Write a function `process_ledger(lines)` that returns a tuple `(balance, invalid_ids)` where `balance` is an integer: the sum in cents of all valid, non-canceled entries, and `invalid_ids` is a sorted list of the ids of invalid reversal/void lines. Example: lines = [('T1','entry',500), ('T2','entry',-200), ('T3','reversal','T2'), ('T4','void','T1'), ('T5','reversal','T2'), ('T6','void','T9')] gives balance 0 (T1 voided, T2 reversed) and invalid_ids ['T5', 'T6'] (T5 reverses an already-canceled entry, T6 references an unknown id). Use only the standard library and exact integer arithmetic (no floats)."}], "completion": [{"role": "assistant", "content": "def process_ledger(lines):\n entries = {} # id -> amount for valid entries\n canceled = set() # ids of reversed/voided entries\n invalid = []\n for tid, ttype, arg in lines:\n if ttype == 'entry':\n entries[tid] = arg\n elif ttype in ('reversal', 'void'):\n target = arg\n if target not in entries or target in canceled:\n invalid.append(tid)\n else:\n canceled.add(target)\n else:\n invalid.append(tid)\n balance = sum(amt for tid, amt in entries.items() if tid not in canceled)\n return balance, sorted(invalid)\n\n\nif __name__ == '__main__':\n lines = [\n ('T1', 'entry', 500),\n ('T2', 'entry', -200),\n ('T3', 'reversal', 'T2'),\n ('T4', 'void', 'T1'),\n ('T5', 'reversal', 'T2'),\n ('T6', 'void', 'T9'),\n ]\n print(process_ledger(lines)) # (0, ['T5', 'T6'])"}], "meta": {"idx": 2363, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 551, "latency_s": 5.0}} +{"prompt": [{"role": "user", "content": "Write a program that computes the inventory valuation of a single product under three costing methods: FIFO, LIFO, and weighted average. The program defines a function `value_inventory(purchases, units_sold, method)` where `purchases` is a list of tuples `(units, unit_cost)` given as strings (e.g. `('100', '10.50')`) in chronological order, `units_sold` is an integer, and `method` is one of `'FIFO'`, `'LIFO'`, or `'WA'`. All arithmetic must use `decimal.Decimal` with `ROUND_HALF_UP` rounding to 2 places for the final answer. FIFO consumes the oldest layers first; LIFO consumes the newest layers first; weighted average computes the average cost of all goods available and applies it to the sold units. The function returns a Decimal representing the value of the REMAINING inventory after the sale. Example: purchases = [('100','10.00'), ('100','12.00')], units_sold = 60, method = 'FIFO' -> 40*10.00 + 100*12.00 = Decimal('1600.00'); with method = 'WA' -> 160*11.00 = Decimal('1760.00'). If units_sold exceeds total units available, raise ValueError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef value_inventory(purchases, units_sold, method):\n layers = [(int(u), Decimal(c)) for u, c in purchases]\n total_units = sum(u for u, _ in layers)\n if units_sold < 0:\n raise ValueError('units_sold must be non-negative')\n if units_sold > total_units:\n raise ValueError('units_sold exceeds units available')\n remaining = units_sold\n if method == 'FIFO':\n layers = layers\n elif method == 'LIFO':\n layers = list(reversed(layers))\n elif method == 'WA':\n total_cost = sum(u * c for u, c in layers)\n avg = total_cost / Decimal(total_units)\n value = avg * Decimal(total_units - units_sold)\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n else:\n raise ValueError('method must be FIFO, LIFO, or WA')\n value = Decimal('0')\n for u, c in layers:\n if remaining <= 0:\n value += u * c\n elif remaining < u:\n value += (u - remaining) * c\n remaining = 0\n else:\n remaining -= u\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\nif __name__ == '__main__':\n purchases = [('100', '10.00'), ('100', '12.00')]\n print(value_inventory(purchases, 60, 'FIFO'))\n print(value_inventory(purchases, 60, 'WA'))\n print(value_inventory(purchases, 60, 'LIFO'))"}], "meta": {"idx": 2366, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 625, "latency_s": 4.3}} +{"prompt": [{"role": "user", "content": "Write a function `taccount_balance(entries)` that computes the balance of a T-account from a list of ledger entries. Each entry is a tuple (side, amount) where side is either 'debit' or 'credit' and amount is a Decimal or a string representing a money amount. Use the `decimal.Decimal` type for all arithmetic and round the final result to 2 decimal places using ROUND_HALF_UP. The balance should be reported as a signed Decimal: positive if debits exceed credits, negative if credits exceed debits, and 0.00 if they are equal. Raise a ValueError if any side is not 'debit' or 'credit' or if any amount cannot be parsed as a Decimal. For example, taccount_balance([('debit', '100.00'), ('credit', '75.50'), ('debit', '25.00'), ('credit', '50.00')]) should return Decimal('-0.50'), since total debits are 125.00 and total credits are 125.50."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, InvalidOperation\n\n\ndef taccount_balance(entries):\n debits = Decimal('0')\n credits = Decimal('0')\n for side, amount in entries:\n if side not in ('debit', 'credit'):\n raise ValueError(\"side must be 'debit' or 'credit'\")\n try:\n amt = amount if isinstance(amount, Decimal) else Decimal(str(amount))\n except (InvalidOperation, TypeError):\n raise ValueError(f\"invalid amount: {amount!r}\")\n if side == 'debit':\n debits += amt\n else:\n credits += amt\n balance = debits - credits\n return balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)"}], "meta": {"idx": 2367, "topic": "general ledger and T-account operations", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 394, "latency_s": 3.9}} +{"prompt": [{"role": "user", "content": "A bookkeeper must split an invoice total across multiple departments using precise Decimal arithmetic. Given an invoice total (e.g., Decimal('100.00')) and a list of department shares specified as percentages (e.g., [33.35, 33.35, 33.30]), compute each department's allocated amount rounded to exactly 2 decimal places using ROUND_HALF_UP. Because rounding can cause the allocations to differ from the total, adjust only the last department so that the sum of all allocations equals the invoice total exactly. Write a function `allocate(total, shares)` that takes a Decimal `total` and a list of Decimal or string percentages, and returns a list of Decimals, each with exactly 2 decimal places. For example, allocate(Decimal('100.00'), ['33.35', '33.35', '33.30']) should return [Decimal('33.35'), Decimal('33.35'), Decimal('33.30')], while allocate(Decimal('10.00'), ['33.33', '33.33', '33.34']) should return [Decimal('3.33'), Decimal('3.33'), Decimal('3.34')]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef allocate(total, shares):\n total = Decimal(total)\n shares = [Decimal(s) for s in shares]\n allocations = []\n for share in shares[:-1]:\n amount = (total * share / Decimal('100')).quantize(TWO, rounding=ROUND_HALF_UP)\n allocations.append(amount)\n remainder = total - sum(allocations)\n allocations.append(remainder.quantize(TWO, rounding=ROUND_HALF_UP))\n return allocations\n\nif __name__ == '__main__':\n print(allocate(Decimal('100.00'), ['33.35', '33.35', '33.30']))\n print(allocate(Decimal('10.00'), ['33.33', '33.33', '33.34']))\n print(allocate(Decimal('20.00'), ['50', '50']))"}], "meta": {"idx": 2369, "topic": "currency rounding rules with the Decimal type", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 427, "latency_s": 3.0}} +{"prompt": [{"role": "user", "content": "You are given journal entries as a list of tuples (entry_id, lines), where lines is a list of (account, side, amount) with side 'D' (debit) or 'C' (credit) and amount a monetary string; parse every amount to cents exactly using Decimal with ROUND_HALF_UP. First, compute each entry's signed imbalance (total debits minus total credits) and flag every entry whose imbalance is nonzero as faulty. Second, post ALL entries anyway and build a trial balance: for each account compute its net position (debits minus credits), show accounts alphabetically, put a positive net in the debit column and a negative net (as a positive number) in the credit column, omit accounts with zero net, and report total debit, total credit, and the overall imbalance (total debit minus total credit). Finally, if the overall imbalance is nonzero, find the minimal set of entries whose removal makes the trial balance balance \u2014 mathematically, the smallest-count subset of faulty entries whose signed imbalances sum to the overall imbalance (removing an entry reduces the imbalance by its own imbalance), breaking ties by the lexicographically smallest sorted tuple of entry IDs; note that faulty entries with canceling errors may legitimately remain. Worked example: entries E1:(Cash D 500.00, Capital C 500.00), E2:(Equipment D 300.00, Accounts Payable C 300.00), E3:(Inventory D 120.00, Accounts Payable C 100.00), E4:(Inventory D 45.00, Cash C 45.00), E5:(Rent D 60.00, Cash C 80.00), E6:(Sales C 30.00, Cash D 30.00), E7:(Supplies D 130.00, Cash C 100.00) yield faulty entries E3 (+20.00), E5 (-20.00), E7 (+30.00); the trial balance is Accounts Payable C 400.00, Cash D 305.00, Capital C 500.00, Equipment D 300.00, Inventory D 165.00, Rent D 60.00, Sales C 30.00, Supplies D 130.00 with total debit 960.00, total credit 930.00, imbalance 30.00, and the minimal removal set is ['E7'] because E3 and E5 cancel each other out."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom itertools import combinations\n\nCENT = Decimal(\"0.01\")\n\n\ndef to_cent(value):\n \"\"\"Parse a monetary value exactly to cents using banker-safe half-up rounding.\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef solve_trial_balance(entries):\n \"\"\"entries: list of (entry_id, [(account, side, amount), ...]).\n side is 'D' (debit) or 'C' (credit).\n Returns a report dict with faulty entries, the trial balance,\n totals, overall imbalance, and the minimal removal set.\n \"\"\"\n balances = {}\n imbalances = {}\n\n for entry_id, lines in entries:\n entry_imb = Decimal(\"0.00\")\n for account, side, amount in lines:\n amt = to_cent(amount)\n sign = 1 if side == \"D\" else -1\n key = account\n balances[key] = balances.get(key, Decimal(\"0.00\")) + sign * amt\n entry_imb += sign * amt\n imbalances[entry_id] = entry_imb\n\n # Faulty entries: nonzero signed imbalance (debits - credits).\n faulty = sorted((eid, imb) for eid, imb in imbalances.items() if imb != 0)\n\n # Build the trial balance from ALL entries (they are posted anyway).\n trial_balance = []\n total_debit = Decimal(\"0.00\")\n total_credit = Decimal(\"0.00\")\n for account in sorted(balances):\n net = balances[account]\n if net == 0:\n continue\n if net > 0:\n trial_balance.append((account, net, Decimal(\"0.00\")))\n total_debit += net\n else:\n trial_balance.append((account, Decimal(\"0.00\"), -net))\n total_credit += -net\n\n overall_imbalance = total_debit - total_credit\n\n # Minimal removal: removing subset T changes the imbalance by\n # -(sum of imbalances in T), so we need sum(T) == overall_imbalance.\n # Search by increasing size; combinations over sorted IDs are emitted\n # in lexicographic order, so the first hit wins the tie-break.\n target = overall_imbalance\n minimal_removal = []\n found = False\n for k in range(len(faulty) + 1):\n for combo in combinations(faulty, k):\n if sum((imb for _, imb in combo), Decimal(\"0.00\")) == target:\n minimal_removal = sorted(eid for eid, _ in combo)\n found = True\n break\n if found:\n break\n\n def fmt(d):\n return str(d.quantize(CENT, rounding=ROUND_HALF_UP))\n\n return {\n \"unbalanced_entries\": [[eid, fmt(imb)] for eid, imb in faulty],\n \"trial_balance\": [[acct, fmt(dr), fmt(cr)] for acct, dr, cr in trial_balance],\n \"total_debit\": fmt(total_debit),\n \"total_credit\": fmt(total_credit),\n \"imbalance\": fmt(overall_imbalance),\n \"minimal_removal_set\": minimal_removal,\n }\n\n\nif __name__ == \"__main__\":\n entries = [\n (\"E1\", [(\"Cash\", \"D\", \"500.00\"), (\"Capital\", \"C\", \"500.00\")]),\n (\"E2\", [(\"Equipment\", \"D\", \"300.00\"), (\"Accounts Payable\", \"C\", \"300.00\")]),\n (\"E3\", [(\"Inventory\", \"D\", \"120.00\"), (\"Accounts Payable\", \"C\", \"100.00\")]),\n (\"E4\", [(\"Inventory\", \"D\", \"45.00\"), (\"Cash\", \"C\", \"45.00\")]),\n (\"E5\", [(\"Rent\", \"D\", \"60.00\"), (\"Cash\", \"C\", \"80.00\")]),\n (\"E6\", [(\"Sales\", \"C\", \"30.00\"), (\"Cash\", \"D\", \"30.00\")]),\n (\"E7\", [(\"Supplies\", \"D\", \"130.00\"), (\"Cash\", \"C\", \"100.00\")]),\n ]\n\n report = solve_trial_balance(entries)\n\n print(\"Faulty entries:\")\n for eid, imb in report[\"unbalanced_entries\"]:\n signed = \"+\" + imb if not imb.startswith(\"-\") else imb\n print(\" {} imbalance {}\".format(eid, signed))\n\n print(\"\\nTrial balance:\")\n print(\" {:<20} {:>12} {:>12}\".format(\"Account\", \"Debit\", \"Credit\"))\n for acct, dr, cr in report[\"trial_balance\"]:\n print(\" {:<20} {:>12} {:>12}\".format(acct, dr, cr))\n print(\" {:<20} {:>12} {:>12}\".format(\"TOTAL\", report[\"total_debit\"], report[\"total_credit\"]))\n print(\" Imbalance (Dr - Cr): {}\".format(report[\"imbalance\"]))\n print(\"\\nMinimal removal set: {}\".format(report[\"minimal_removal_set\"]))"}], "meta": {"idx": 2326, "topic": "trial balance construction and imbalance detection", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1569, "latency_s": 156.7}} +{"prompt": [{"role": "user", "content": "You are building a small fixed-asset ledger for a bookkeeping system. Write a function `depreciation_schedule(cost, salvage, useful_life, method, rate=None)` that returns the full depreciation schedule as a list of (year, depreciation_expense, accumulated_depreciation, book_value) tuples, where all monetary values are `Decimal` rounded to 2 places with ROUND_HALF_UP. `method` is either 'straight_line' or 'declining_balance'. For straight-line, each year's expense is (cost - salvage) / useful_life, with a final-year plug so the ending book value equals salvage exactly. For declining balance, each year's expense is the current book value multiplied by `rate` (a Decimal or string like '0.40'), but the expense is capped so the book value never drops below salvage; once it would, the final year takes the remaining difference down to salvage and subsequent years have zero expense. For example, with cost=Decimal('10000.00'), salvage=Decimal('1000.00'), useful_life=5, method='declining_balance', rate='0.40', the schedule's book values after each year are 6000.00, 3600.00, 2160.00, 1296.00, and 1000.00 (the last year's expense is capped at 296.00). The function must raise ValueError for a non-positive useful_life, a salvage greater than cost, or a missing/invalid rate when method is 'declining_balance'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _q(value):\n return Decimal(value).quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef depreciation_schedule(cost, salvage, useful_life, method, rate=None):\n cost = _q(cost)\n salvage = _q(salvage)\n\n if useful_life <= 0:\n raise ValueError('useful_life must be a positive integer')\n if salvage > cost:\n raise ValueError('salvage value cannot exceed cost')\n if method not in ('straight_line', 'declining_balance'):\n raise ValueError('unknown method: %r' % (method,))\n\n schedule = []\n accum = Decimal('0.00')\n\n if method == 'straight_line':\n base = cost - salvage\n expense = _q(base / Decimal(useful_life))\n remaining = base\n for year in range(1, useful_life + 1):\n if year < useful_life:\n dep = min(expense, remaining)\n else:\n dep = remaining\n remaining -= dep\n accum += dep\n book = cost - accum\n schedule.append((year, _q(dep), _q(accum), _q(book)))\n else:\n if rate is None:\n raise ValueError('rate is required for declining_balance')\n try:\n rate = Decimal(rate)\n except Exception:\n raise ValueError('rate must be convertible to Decimal')\n if rate <= 0 or rate > 1:\n raise ValueError('rate must be in (0, 1]')\n book = cost\n for year in range(1, useful_life + 1):\n if book <= salvage:\n dep = Decimal('0.00')\n else:\n dep = _q(book * rate)\n if book - dep < salvage:\n dep = book - salvage\n book -= dep\n accum += dep\n schedule.append((year, _q(dep), _q(accum), _q(book)))\n\n return schedule\n\nif __name__ == '__main__':\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5,\n 'declining_balance', rate='0.40'):\n print(row)\n print()\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5,\n 'straight_line'):\n print(row)"}], "meta": {"idx": 2370, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 901, "latency_s": 8.3}} +{"prompt": [{"role": "user", "content": "You are auditing a company ledger for duplicate and anomalous transactions. Each transaction is given as a dict with keys \"id\" (int), \"date\" (ISO string YYYY-MM-DD), \"description\" (str), and \"amount\" (str representing a decimal number, possibly negative). Write a function `audit_ledger(transactions)` that returns a list of tuples `(id, reason)` for flagged transactions, preserving the input order of the flagged transactions, applying these rules with priority (only the highest-priority matching rule is reported per transaction): 1) \"duplicate\" \u2014 the transaction has the same date, description, and amount as some earlier transaction in the list; 2) \"sub-cent\" \u2014 the amount, when quantized to 2 decimal places with ROUND_HALF_UP, differs from the original amount (i.e., it contains fractions of a cent); 3) \"reversal\" \u2014 the transaction's amount is the exact negation of an earlier transaction's amount with the same description, and the two dates are at most 7 days apart. Use `Decimal` for all monetary arithmetic; do not use floats. Example: transactions = [{\"id\":1,\"date\":\"2024-03-01\",\"description\":\"Office supplies\",\"amount\":\"45.99\"}, {\"id\":2,\"date\":\"2024-03-01\",\"description\":\"Office supplies\",\"amount\":\"45.99\"}, {\"id\":3,\"date\":\"2024-03-03\",\"description\":\"Client refund\",\"amount\":\"-120.00\"}, {\"id\":4,\"date\":\"2024-03-05\",\"description\":\"Client refund\",\"amount\":\"120.00\"}, {\"id\":5,\"date\":\"2024-03-06\",\"description\":\"Bank fee\",\"amount\":\"3.456\"}] must return [(2, \"duplicate\"), (4, \"reversal\"), (5, \"sub-cent\")] \u2014 id 2 duplicates id 1 exactly, id 4 reverses id 3 within 7 days, and id 5 has a sub-cent amount."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\n\ndef audit_ledger(transactions):\n \"\"\"Flag duplicate and anomalous ledger transactions.\n\n Each transaction is a dict with keys: id (int), date (ISO string),\n description (str), amount (str parseable as Decimal).\n\n Returns a list of (id, reason) tuples in input order, where reason is\n one of \"duplicate\", \"sub-cent\", or \"reversal\" (checked in that\n priority order, one reason per transaction at most).\n \"\"\"\n CENT = Decimal(\"0.01\")\n parsed = []\n for tx in transactions:\n parsed.append({\n \"id\": tx[\"id\"],\n \"date\": date.fromisoformat(tx[\"date\"]),\n \"description\": tx[\"description\"],\n \"amount\": Decimal(tx[\"amount\"]),\n })\n\n flags = []\n seen_exact = set() # (date, description, amount) of earlier txns\n earlier = [] # list of already-processed transactions\n\n for tx in parsed:\n reason = None\n\n exact_key = (tx[\"date\"], tx[\"description\"], tx[\"amount\"])\n if exact_key in seen_exact:\n reason = \"duplicate\"\n\n if reason is None:\n rounded = tx[\"amount\"].quantize(CENT, rounding=ROUND_HALF_UP)\n if rounded != tx[\"amount\"]:\n reason = \"sub-cent\"\n\n if reason is None:\n for prev in earlier:\n if (\n prev[\"description\"] == tx[\"description\"]\n and prev[\"amount\"] == -tx[\"amount\"]\n and abs((tx[\"date\"] - prev[\"date\"]).days) <= 7\n ):\n reason = \"reversal\"\n break\n\n if reason is not None:\n flags.append((tx[\"id\"], reason))\n\n seen_exact.add(exact_key)\n earlier.append(tx)\n\n return flags\n\n\nif __name__ == \"__main__\":\n transactions = [\n {\"id\": 1, \"date\": \"2024-03-01\", \"description\": \"Office supplies\", \"amount\": \"45.99\"},\n {\"id\": 2, \"date\": \"2024-03-01\", \"description\": \"Office supplies\", \"amount\": \"45.99\"},\n {\"id\": 3, \"date\": \"2024-03-03\", \"description\": \"Client refund\", \"amount\": \"-120.00\"},\n {\"id\": 4, \"date\": \"2024-03-05\", \"description\": \"Client refund\", \"amount\": \"120.00\"},\n {\"id\": 5, \"date\": \"2024-03-06\", \"description\": \"Bank fee\", \"amount\": \"3.456\"},\n ]\n result = audit_ledger(transactions)\n print(result)\n assert result == [(2, \"duplicate\"), (4, \"reversal\"), (5, \"sub-cent\")]"}], "meta": {"idx": 2365, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "novita", "in_tokens": 198, "out_tokens": 1680, "latency_s": 13.0}} +{"prompt": [{"role": "user", "content": "You are given a list of budget line items and a list of actual transactions for a small business month. Each budget line is a dict with 'category' and 'budget_amount' (a string like '500.00'). Each actual transaction is a dict with 'category' and 'amount'. Write a function variance_report(budget_lines, actuals) that returns a dict mapping each category to a dict with keys 'budget', 'actual', 'variance', and 'variance_pct'. The variance is budget minus actual (positive means under budget, a favorable result). The variance_pct is the variance divided by the budget, expressed as a percentage and rounded to two decimal places using Decimal ROUND_HALF_UP; if the budget is zero, variance_pct should be None. All monetary amounts must be computed with Decimal and rounded to two decimal places with ROUND_HALF_UP. Categories that appear in actuals but have no budget line are treated as having a zero budget. Example: budget_lines = [{'category': 'office', 'budget_amount': '500.00'}, {'category': 'travel', 'budget_amount': '300.00'}], actuals = [{'category': 'office', 'amount': '425.50'}, {'category': 'meals', 'amount': '80.00'}] should return {'office': {'budget': Decimal('500.00'), 'actual': Decimal('425.50'), 'variance': Decimal('74.50'), 'variance_pct': Decimal('14.90')}, 'travel': {'budget': Decimal('300.00'), 'actual': Decimal('0.00'), 'variance': Decimal('300.00'), 'variance_pct': Decimal('100.00')}, 'meals': {'budget': Decimal('0.00'), 'actual': Decimal('80.00'), 'variance': Decimal('-80.00'), 'variance_pct': None}}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\nZERO = Decimal('0.00')\n\n\ndef _money(value):\n return Decimal(value).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef variance_report(budget_lines, actuals):\n categories = {}\n for line in budget_lines:\n cat = line['category']\n categories.setdefault(cat, {'budget': ZERO, 'actual': ZERO})\n categories[cat]['budget'] += Decimal(line['budget_amount'])\n for txn in actuals:\n cat = txn['category']\n categories.setdefault(cat, {'budget': ZERO, 'actual': ZERO})\n categories[cat]['actual'] += Decimal(txn['amount'])\n\n report = {}\n for cat, amounts in categories.items():\n budget = _money(amounts['budget'])\n actual = _money(amounts['actual'])\n variance = _money(budget - actual)\n if budget == ZERO:\n variance_pct = None\n else:\n pct = (variance / budget) * Decimal('100')\n variance_pct = pct.quantize(TWO, rounding=ROUND_HALF_UP)\n report[cat] = {\n 'budget': budget,\n 'actual': actual,\n 'variance': variance,\n 'variance_pct': variance_pct,\n }\n return report\n\n\nif __name__ == '__main__':\n budget_lines = [\n {'category': 'office', 'budget_amount': '500.00'},\n {'category': 'travel', 'budget_amount': '300.00'},\n ]\n actuals = [\n {'category': 'office', 'amount': '425.50'},\n {'category': 'meals', 'amount': '80.00'},\n ]\n result = variance_report(budget_lines, actuals)\n for cat in sorted(result):\n print(cat, result[cat])\n assert result['office']['variance'] == Decimal('74.50')\n assert result['office']['variance_pct'] == Decimal('14.90')\n assert result['travel']['variance_pct'] == Decimal('100.00')\n assert result['meals']['variance_pct'] is None\n assert result['meals']['variance'] == Decimal('-80.00')\n print('All checks passed.')"}], "meta": {"idx": 2372, "topic": "budget versus actual variance analysis", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 892, "latency_s": 7.9}} +{"prompt": [{"role": "user", "content": "Build the core logic of a small double-entry bookkeeping CLI. Input is a CSV ledger whose first line is the header `date,ref,account,debit,credit`; a transaction is the group of rows sharing the same `ref`, and every amount must parse as a non-negative Decimal with at most two decimal places. A transaction is accepted only if its total debits exactly equal its total credits; rejected transactions contribute nothing to balances, and for each one print `ERROR : off by ` (or `ERROR : bad amount` if any amount fails to parse), with errors sorted by ref. Then print `BALANCE ` (balance = debits \u2212 credits, exactly two decimals) for every account touched by an accepted transaction, sorted by account name. Finally, allocate an overhead pool given as a spec string like `1000.00 Facilities=3 Operations=2 IT=1`: each department's exact share is pool\u00b7weight/\u03a3weights, shares are rounded down to whole cents, and leftover cents are distributed one at a time to departments with the largest fractional remainders (ties broken by department name ascending) so allocations sum exactly to the pool; print `ALLOC ` sorted by department name, then `TOTAL ALLOCATED `. Worked example: for the ledger `date,ref,account,debit,credit / 2024-01-05,T1,Cash,100.00,0.00 / 2024-01-05,T1,Revenue,0.00,100.00 / 2024-01-06,T2,Cash,50.00,0.00 / 2024-01-06,T2,Supplies,20.00,0.00 / 2024-01-06,T2,Accounts Payable,0.00,69.99 / 2024-01-07,T3,Supplies,30.00,0.00 / 2024-01-07,T3,Cash,0.00,30.00` (one row per line) and allocation `1000.00 Facilities=3 Operations=2 IT=1`, the output is exactly: `ERROR T2: off by 0.01`, `BALANCE Cash 70.00`, `BALANCE Revenue -100.00`, `BALANCE Supplies 30.00`, `ALLOC Facilities 500.00`, `ALLOC IT 166.67`, `ALLOC Operations 333.33`, `TOTAL ALLOCATED 1000.00` (each on its own line)."}], "completion": [{"role": "assistant", "content": "import csv\nimport sys\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\nDEMO_LEDGER = \"\"\"date,ref,account,debit,credit\n2024-01-05,T1,Cash,100.00,0.00\n2024-01-05,T1,Revenue,0.00,100.00\n2024-01-06,T2,Cash,50.00,0.00\n2024-01-06,T2,Supplies,20.00,0.00\n2024-01-06,T2,Accounts Payable,0.00,69.99\n2024-01-07,T3,Supplies,30.00,0.00\n2024-01-07,T3,Cash,0.00,30.00\n\"\"\"\n\nDEMO_ALLOC = \"1000.00 Facilities=3 Operations=2 IT=1\"\n\n\ndef parse_money(text):\n \"\"\"Parse a money string: non-negative Decimal with at most 2 decimal places.\"\"\"\n value = Decimal(text.strip())\n if value < ZERO:\n raise ValueError(\"negative amount\")\n if value != value.quantize(CENT, rounding=ROUND_HALF_UP):\n raise ValueError(\"too many decimal places\")\n return value.quantize(CENT)\n\n\ndef process_ledger(ledger_text):\n \"\"\"Return (error_lines, account_balances) for the CSV ledger.\"\"\"\n rows = list(csv.reader(ledger_text.strip().splitlines()))\n entries = {}\n for row in rows[1:]: # skip header\n _date, ref, account, debit_s, credit_s = row\n entries.setdefault(ref, []).append(\n (account, debit_s.strip(), credit_s.strip())\n )\n\n errors = []\n balances = {}\n for ref in sorted(entries):\n parsed = []\n failed = False\n for account, debit_s, credit_s in entries[ref]:\n try:\n parsed.append((account, parse_money(debit_s), parse_money(credit_s)))\n except Exception:\n errors.append(\"ERROR {}: bad amount\".format(ref))\n failed = True\n break\n if failed:\n continue\n\n debits = sum((d for _a, d, _c in parsed), ZERO)\n credits = sum((c for _a, _d, c in parsed), ZERO)\n if debits != credits:\n off = abs(debits - credits).quantize(CENT)\n errors.append(\"ERROR {}: off by {}\".format(ref, off))\n continue\n\n for account, d, c in parsed:\n balances[account] = balances.get(account, ZERO) + d - c\n return errors, balances\n\n\ndef parse_allocation(spec):\n \"\"\"Parse e.g. '1000.00 Facilities=3 Operations=2 IT=1' -> (pool, weights).\"\"\"\n parts = spec.split()\n if not parts:\n raise ValueError(\"empty allocation spec\")\n pool = parse_money(parts[0])\n weights = {}\n for token in parts[1:]:\n name, _sep, w_text = token.partition(\"=\")\n weight = Decimal(w_text)\n if weight < 0 or not name:\n raise ValueError(\"invalid weight token\")\n weights[name] = weight\n if not weights or sum(weights.values(), ZERO) <= 0:\n raise ValueError(\"no positive weight\")\n return pool, weights\n\n\ndef allocate_pool(pool, weights):\n \"\"\"Largest-remainder allocation of pool to departments; sums exactly to pool.\"\"\"\n total_weight = sum(weights.values())\n pool_cents = int((pool / CENT).to_integral_value())\n\n cents = {}\n remainders = []\n for name, weight in weights.items():\n scaled = pool_cents * weight\n floor_cents = scaled // total_weight\n cents[name] = int(floor_cents)\n remainders.append((int(scaled % total_weight), name))\n\n leftover = pool_cents - sum(cents.values())\n remainders.sort(key=lambda item: (-item[0], item[1]))\n for i in range(leftover):\n cents[remainders[i % len(remainders)][1]] += 1\n\n return {name: Decimal(c).quantize(CENT) for name, c in cents.items()}\n\n\ndef run(ledger_text, alloc_spec):\n \"\"\"Produce the full report as a list of lines.\"\"\"\n output = []\n errors, balances = process_ledger(ledger_text)\n output.extend(errors)\n\n for account in sorted(balances):\n output.append(\"BALANCE {} {}\".format(account, balances[account].quantize(CENT)))\n\n pool, weights = parse_allocation(alloc_spec)\n allocations = allocate_pool(pool, weights)\n for name in sorted(allocations):\n output.append(\"ALLOC {} {}\".format(name, allocations[name]))\n total = sum(allocations.values(), ZERO).quantize(CENT)\n output.append(\"TOTAL ALLOCATED {}\".format(total))\n return output\n\n\ndef main(argv):\n if len(argv) >= 3:\n with open(argv[1], \"r\", newline=\"\") as handle:\n ledger_text = handle.read()\n alloc_spec = argv[2]\n else:\n ledger_text = DEMO_LEDGER\n alloc_spec = DEMO_ALLOC\n for line in run(ledger_text, alloc_spec):\n print(line)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)"}], "meta": {"idx": 2354, "topic": "small bookkeeping command-line tool logic", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1634, "latency_s": 60.6}} +{"prompt": [{"role": "user", "content": "You are given a list of invoice records as tuples (invoice_id, customer_or_vendor, amount, direction, due_date), where direction is either 'AR' (accounts receivable, money owed to you) or 'AP' (accounts payable, money you owe), amount is a string like '1250.75', and due_date is a string 'YYYY-MM-DD'. Given an as-of date, build an aging report that buckets each invoice by days overdue: 'Current' (not yet due), '1-30', '31-60', '61-90', 'Over 90'. For each direction, produce a bucket-to-total mapping (using Decimal arithmetic, rounded to cents) and a net position: total AR minus total AP. Invoices with an amount of zero should be ignored. Example: invoices [('I1','Acme','100.00','AR','2024-01-01'), ('I2','Beta','50.50','AP','2024-02-01')] with as-of date '2024-01-15' yields AR buckets {'Current': Decimal('0'), '1-30': Decimal('0'), '31-60': Decimal('0'), '61-90': Decimal('0'), 'Over 90': Decimal('0')} plus {'1-30': Decimal('100.00')}\u2014that is, I1 is 14 days overdue so it goes in '1-30', and I2 is not yet due so AP 'Current' is Decimal('50.50'); net position is Decimal('100.00') - Decimal('50.50') = Decimal('49.50'). Write a function aging_report(invoices, as_of_date) returning a dict {'AR': {bucket: Decimal}, 'AP': {bucket: Decimal}, 'net': Decimal} where every bucket appears in each mapping."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom datetime import date\n\nBUCKETS = ['Current', '1-30', '31-60', '61-90', 'Over 90']\n\n\ndef _bucket_for(days_overdue):\n if days_overdue <= 0:\n return 'Current'\n if days_overdue <= 30:\n return '1-30'\n if days_overdue <= 60:\n return '31-60'\n if days_overdue <= 90:\n return '61-90'\n return 'Over 90'\n\n\ndef aging_report(invoices, as_of_date):\n as_of = date.fromisoformat(as_of_date)\n result = {\n 'AR': {b: Decimal('0.00') for b in BUCKETS},\n 'AP': {b: Decimal('0.00') for b in BUCKETS},\n }\n for invoice_id, party, amount_str, direction, due_date_str in invoices:\n amount = Decimal(amount_str)\n if amount == 0:\n continue\n if direction not in ('AR', 'AP'):\n raise ValueError('direction must be AR or AP: %r' % direction)\n due = date.fromisoformat(due_date_str)\n days_overdue = (as_of - due).days\n bucket = _bucket_for(days_overdue)\n result[direction][bucket] += amount\n for direction in ('AR', 'AP'):\n for b in BUCKETS:\n result[direction][b] = result[direction][b].quantize(Decimal('0.01'))\n result['net'] = (sum(result['AR'].values(), Decimal('0.00'))\n - sum(result['AP'].values(), Decimal('0.00'))).quantize(Decimal('0.01'))\n return result\n\n\nif __name__ == '__main__':\n invoices = [\n ('I1', 'Acme', '100.00', 'AR', '2024-01-01'),\n ('I2', 'Beta', '50.50', 'AP', '2024-02-01'),\n ]\n report = aging_report(invoices, '2024-01-15')\n print(report['AR']['1-30']) # 100.00\n print(report['AP']['Current']) # 50.50\n print(report['net']) # 49.50"}], "meta": {"idx": 2373, "topic": "accounts receivable and payable aging reports", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 770, "latency_s": 10.3}} +{"prompt": [{"role": "user", "content": "A bookkeeper records purchases of office supplies in a foreign currency and must report the total in the reporting currency, including realized FX gains/losses. You are given a list of purchases, each as a tuple (date, amount_foreign, rate_at_purchase), and a closing exchange rate at the reporting date. Using the `decimal.Decimal` type with ROUND_HALF_UP quantization to 0.01, compute: (1) the total foreign amount, (2) the total in reporting currency valued at each purchase's own rate (the booked cost), and (3) the FX gain or loss defined as booked_cost minus the same total foreign amount revalued at the closing rate (a positive result is a loss, a negative result is a gain). All monetary outputs must be rounded to 2 decimal places. For example, purchases [('2024-01-05', Decimal('100.00'), Decimal('1.10')), ('2024-02-10', Decimal('200.50'), Decimal('1.25'))] with closing rate Decimal('1.20') give total foreign Decimal('300.50'), booked cost Decimal('350.63'), revalued amount Decimal('360.60'), and FX loss Decimal('-9.97') (i.e., a gain of 9.97). Write a function `fx_report(purchases, closing_rate)` returning a dict with keys 'total_foreign', 'booked_cost', 'revalued_amount', 'fx_gain_loss'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _q(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef fx_report(purchases, closing_rate):\n two = Decimal('0.01')\n total_foreign = Decimal('0')\n booked_cost = Decimal('0')\n for _date, amount_foreign, rate in purchases:\n amount_foreign = Decimal(amount_foreign)\n rate = Decimal(rate)\n total_foreign += amount_foreign\n booked_cost += amount_foreign * rate\n closing_rate = Decimal(closing_rate)\n revalued_amount = total_foreign * closing_rate\n fx_gain_loss = booked_cost - revalued_amount\n return {\n 'total_foreign': _q(total_foreign),\n 'booked_cost': _q(booked_cost),\n 'revalued_amount': _q(revalued_amount),\n 'fx_gain_loss': _q(fx_gain_loss),\n }\n\n\nif __name__ == '__main__':\n purchases = [\n ('2024-01-05', Decimal('100.00'), Decimal('1.10')),\n ('2024-02-10', Decimal('200.50'), Decimal('1.25')),\n ]\n result = fx_report(purchases, Decimal('1.20'))\n print(result)\n assert result['total_foreign'] == Decimal('300.50')\n assert result['booked_cost'] == Decimal('350.63')\n assert result['revalued_amount'] == Decimal('360.60')\n assert result['fx_gain_loss'] == Decimal('-9.97')"}], "meta": {"idx": 2374, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 638, "latency_s": 14.1}} +{"prompt": [{"role": "user", "content": "Write a function `next_invoice_number(last_numbers, prefix)` that generates invoice numbers for a small bookkeeping system. Invoice numbers look like `INV-2024-0007`: the prefix (e.g. `INV`), a 4-digit year, a hyphen, and a 4-digit zero-padded sequence number that resets each year. Given a list `last_numbers` of previously issued invoice number strings (possibly empty) and a string `prefix`, return the next invoice number as a string. The sequence number should be one greater than the highest sequence number issued in the current year (use the current calendar year from `datetime.date.today()`); if none exist for the current year, start at 1. Ignore numbers with a different prefix or a malformed format. Example: if today is in 2024 and `last_numbers = ['INV-2023-0099', 'INV-2024-0007', 'BAD', 'INV-2024-0003']`, then `next_invoice_number(last_numbers, 'INV')` returns `'INV-2024-0008'`."}], "completion": [{"role": "assistant", "content": "import re\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\n\ndef next_invoice_number(last_numbers, prefix):\n year = date.today().year\n pattern = re.compile(r'^' + re.escape(prefix) + r'-(\\d{4})-(\\d{4})$')\n max_seq = 0\n for num in last_numbers:\n m = pattern.match(num)\n if m and int(m.group(1)) == year:\n seq = int(m.group(2))\n if seq > max_seq:\n max_seq = seq\n return f\"{prefix}-{year:04d}-{max_seq + 1:04d}\"\n\n\nif __name__ == '__main__':\n example = ['INV-2023-0099', 'INV-2024-0007', 'BAD', 'INV-2024-0003']\n print(next_invoice_number(example, 'INV'))\n print(next_invoice_number([], 'INV'))"}], "meta": {"idx": 2377, "topic": "invoice generation, numbering, and parsing", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 410, "latency_s": 2.7}} +{"prompt": [{"role": "user", "content": "Implement a general ledger with T-account support. Each account has a name and a normal balance side ('debit' or 'credit'). Entries are posted as (debit_account, credit_account, amount, description) with amounts as Decimal rounded to 2 places (raise ValueError if an amount has more than 2 decimal places). For each account, maintain debit and credit running totals, and compute the balance as debit_total - credit_total for debit-normal accounts, or credit_total - debit_total for credit-normal accounts (always non-negative if used correctly). Implement a class Ledger with methods post(debit_account, credit_account, amount, description), balance(account) returning the signed balance (positive means normal-side balance), and trial_balance() returning a dict mapping each account name to its signed balance, plus a method is_balanced() that returns True if total debits posted equals total credits posted. Example: ledger = Ledger(); ledger.add_account('Cash', 'debit'); ledger.add_account('Revenue', 'credit'); ledger.post('Cash', 'Revenue', Decimal('150.25'), 'Sale'); then balance('Cash') == Decimal('150.25'), balance('Revenue') == Decimal('150.25'), and is_balanced() is True. Posting to an unknown account should raise KeyError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\nclass Account:\n def __init__(self, name, normal_side):\n if normal_side not in ('debit', 'credit'):\n raise ValueError(\"normal_side must be 'debit' or 'credit'\")\n self.name = name\n self.normal_side = normal_side\n self.debit_total = Decimal('0.00')\n self.credit_total = Decimal('0.00')\n\n\nclass Ledger:\n def __init__(self):\n self.accounts = {}\n\n def add_account(self, name, normal_side):\n if name in self.accounts:\n raise ValueError(f\"Account '{name}' already exists\")\n self.accounts[name] = Account(name, normal_side)\n\n def _get_account(self, name):\n if name not in self.accounts:\n raise KeyError(f\"Unknown account: '{name}'\")\n return self.accounts[name]\n\n @staticmethod\n def _validate_amount(amount):\n if not isinstance(amount, Decimal):\n amount = Decimal(str(amount))\n amount = amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if amount != amount.quantize(Decimal('0.01')):\n raise ValueError(\"Amount has more than 2 decimal places\")\n if amount <= 0:\n raise ValueError(\"Amount must be positive\")\n return amount\n\n def post(self, debit_account, credit_account, amount, description=''):\n amount = self._validate_amount(amount)\n debit_acct = self._get_account(debit_account)\n credit_acct = self._get_account(credit_account)\n debit_acct.debit_total += amount\n credit_acct.credit_total += amount\n\n def balance(self, account):\n acct = self._get_account(account)\n if acct.normal_side == 'debit':\n return (acct.debit_total - acct.credit_total).quantize(Decimal('0.01'))\n return (acct.credit_total - acct.debit_total).quantize(Decimal('0.01'))\n\n def trial_balance(self):\n return {name: self.balance(name) for name in self.accounts}\n\n def is_balanced(self):\n total_debits = sum(a.debit_total for a in self.accounts.values())\n total_credits = sum(a.credit_total for a in self.accounts.values())\n return total_debits == total_credits\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add_account('Cash', 'debit')\n ledger.add_account('Revenue', 'credit')\n ledger.post('Cash', 'Revenue', Decimal('150.25'), 'Sale')\n assert ledger.balance('Cash') == Decimal('150.25')\n assert ledger.balance('Revenue') == Decimal('150.25')\n assert ledger.is_balanced()\n print(ledger.trial_balance())"}], "meta": {"idx": 2335, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 974, "latency_s": 195.2}} +{"prompt": [{"role": "user", "content": "You maintain a petty cash fund under the imprest system: the fund starts with a fixed float (the imprest amount), every cash payment is logged as a voucher, and periodic replenishments top the fund back up. Write a function process_petty_cash_log(imprest, log_lines) where imprest is a string such as '100.00' and log_lines is a list of strings, each of the form 'DATE VOUCHER id category gross tax', 'DATE COUNT amount', or 'DATE REPLENISH amount' (dates are YYYY-MM-DD). Because cash is paid in coins, a voucher reduces cash on hand by the gross amount rounded to the nearest 0.05 using ROUND_HALF_UP ties; a COUNT records the discrepancy (counted minus expected cash at that moment) but does not change the expected balance; a REPLENISH adds the stated amount to cash and is compared against the coin-rounded total of vouchers since the previous replenishment (recording the variance), after which that pending accumulator resets. Record an error and skip the line for: malformed lines (wrong token count or bad date format), non-numeric or non-positive voucher gross, tax below 0 or above gross, negative COUNT or REPLENISH amounts, or a duplicate voucher id, with messages formatted exactly as 'line N: ' (e.g. 'line 5: duplicate voucher id V001'). Return a dict with keys 'category_totals' (exact gross per category), 'total_tax', 'total_vouchers_exact', 'total_vouchers_coin', 'rounding_adjustment' (coin minus exact), 'count_discrepancies' (list of [date, expected, counted, discrepancy]), 'replenishments' (list of [date, amount, expected, variance]), 'errors', 'final_cash', and 'pending_vouchers' (coin-rounded voucher total since the last replenishment); all monetary values must be Decimal. Worked example: with imprest '100.00' and the lines ['2024-03-01 VOUCHER V001 postage 3.42 0.00', '2024-03-01 VOUCHER V002 supplies 12.34 1.23', '2024-03-02 COUNT 84.20', '2024-03-02 VOUCHER V003 postage 1.13 0.00', '2024-03-03 VOUCHER V001 postage 9.99 0.00', '2024-03-04 REPLENISH 16.90', '2024-03-05 VOUCHER V004 coffee 7.77 0.50'], the coin-rounded payouts are 3.40, 12.35, 1.15 and 7.75, so the count at line 3 shows a discrepancy of -0.05 (expected 84.25, counted 84.20), the duplicate at line 5 is an error, the replenishment of 16.90 exactly matches the pending vouchers (variance 0.00), and the result has category_totals {'postage': 4.55, 'supplies': 12.34, 'coffee': 7.77}, total_tax 1.73, total_vouchers_exact 24.66, total_vouchers_coin 24.65, rounding_adjustment -0.01, final_cash 92.25, and pending_vouchers 7.75."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, InvalidOperation\nfrom datetime import datetime\n\nFIVE_CENTS = Decimal(\"0.05\")\nZERO = Decimal(\"0\")\n\n\ndef _coin_round(amount):\n \"\"\"Round a Decimal amount to the nearest 0.05, ties away from zero (half-up).\"\"\"\n return (amount / FIVE_CENTS).quantize(Decimal(\"1\"), rounding=ROUND_HALF_UP) * FIVE_CENTS\n\n\ndef _parse_amount(text):\n try:\n return Decimal(text)\n except InvalidOperation:\n return None\n\n\ndef _valid_date(text):\n try:\n datetime.strptime(text, \"%Y-%m-%d\")\n return True\n except ValueError:\n return False\n\n\ndef process_petty_cash_log(imprest, log_lines):\n imprest_d = Decimal(imprest)\n cash = imprest_d\n\n seen_ids = set()\n errors = []\n category_totals = {}\n total_tax = ZERO\n total_exact = ZERO\n total_coin = ZERO\n pending = ZERO\n count_discrepancies = []\n replenishments = []\n\n for idx, raw in enumerate(log_lines, 1):\n parts = raw.split()\n if not parts:\n continue\n\n if len(parts) < 3 or not _valid_date(parts[0]):\n errors.append(\"line %d: malformed line\" % idx)\n continue\n\n date, kind = parts[0], parts[1]\n\n if kind == \"VOUCHER\":\n if len(parts) != 6:\n errors.append(\"line %d: malformed line\" % idx)\n continue\n vid, category, gross_s, tax_s = parts[2], parts[3], parts[4], parts[5]\n gross = _parse_amount(gross_s)\n tax = _parse_amount(tax_s)\n if gross is None or tax is None or gross <= ZERO or tax < ZERO or tax > gross:\n errors.append(\"line %d: invalid voucher amount\" % idx)\n continue\n if vid in seen_ids:\n errors.append(\"line %d: duplicate voucher id %s\" % (idx, vid))\n continue\n seen_ids.add(vid)\n\n paid = _coin_round(gross)\n cash -= paid\n pending += paid\n total_exact += gross\n total_coin += paid\n total_tax += tax\n category_totals[category] = category_totals.get(category, ZERO) + gross\n\n elif kind == \"COUNT\":\n if len(parts) != 3:\n errors.append(\"line %d: malformed line\" % idx)\n continue\n counted = _parse_amount(parts[2])\n if counted is None or counted < ZERO:\n errors.append(\"line %d: invalid count amount\" % idx)\n continue\n count_discrepancies.append([date, cash, counted, counted - cash])\n\n elif kind == \"REPLENISH\":\n if len(parts) != 3:\n errors.append(\"line %d: malformed line\" % idx)\n continue\n amount = _parse_amount(parts[2])\n if amount is None or amount < ZERO:\n errors.append(\"line %d: invalid replenishment amount\" % idx)\n continue\n replenishments.append([date, amount, pending, amount - pending])\n cash += amount\n pending = ZERO\n\n else:\n errors.append(\"line %d: malformed line\" % idx)\n\n return {\n \"category_totals\": category_totals,\n \"total_tax\": total_tax,\n \"total_vouchers_exact\": total_exact,\n \"total_vouchers_coin\": total_coin,\n \"rounding_adjustment\": total_coin - total_exact,\n \"count_discrepancies\": count_discrepancies,\n \"replenishments\": replenishments,\n \"errors\": errors,\n \"final_cash\": cash,\n \"pending_vouchers\": pending,\n }\n\n\nif __name__ == \"__main__\":\n lines = [\n \"2024-03-01 VOUCHER V001 postage 3.42 0.00\",\n \"2024-03-01 VOUCHER V002 supplies 12.34 1.23\",\n \"2024-03-02 COUNT 84.20\",\n \"2024-03-02 VOUCHER V003 postage 1.13 0.00\",\n \"2024-03-03 VOUCHER V001 postage 9.99 0.00\",\n \"2024-03-04 REPLENISH 16.90\",\n \"2024-03-05 VOUCHER V004 coffee 7.77 0.50\",\n ]\n report = process_petty_cash_log(\"100.00\", lines)\n for key, value in report.items():\n print(key, \"=\", value)"}], "meta": {"idx": 2358, "topic": "petty cash logs and replenishment", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1710, "latency_s": 96.1}} +{"prompt": [{"role": "user", "content": "Write a function reconcile_bank_statement(book_balance, bank_balance, entries) that reconciles a company's cash book against a bank statement. book_balance and bank_balance are strings representing Decimal amounts (the cash book ending balance and the bank statement ending balance). entries is a list of tuples (description, kind, amount) where kind is one of 'deposit_in_transit' (a deposit recorded in the cash book but not yet on the bank statement), 'outstanding_check' (a check recorded in the cash book but not yet cleared the bank), or 'bank_fee' (a fee charged by the bank but not yet recorded in the cash book). The function must return a dict with keys 'adjusted_bank_balance' (bank_balance plus deposits in transit minus outstanding checks, rounded to 2 decimal places with ROUND_HALF_UP), 'adjusted_book_balance' (book_balance minus bank fees, rounded the same way), and 'difference' (adjusted_bank_balance minus adjusted_book_balance, rounded the same way; 0.00 means the accounts reconcile). Example: book_balance='1200.00', bank_balance='1350.00', entries=[('Payroll check 102','outstanding_check','250.00'),('Deposit 5/12','deposit_in_transit','100.00'),('Monthly fee','bank_fee','12.50')] should return {'adjusted_bank_balance': '1200.00', 'adjusted_book_balance': '1187.50', 'difference': '12.50'}. Use only the standard library and Decimal arithmetic throughout; return all amounts as strings with exactly two decimal places."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef reconcile_bank_statement(book_balance, bank_balance, entries):\n quant = lambda d: d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n book = Decimal(book_balance)\n bank = Decimal(bank_balance)\n adjusted_bank = bank\n adjusted_book = book\n for _desc, kind, amount in entries:\n amt = Decimal(amount)\n if kind == 'deposit_in_transit':\n adjusted_bank += amt\n elif kind == 'outstanding_check':\n adjusted_bank -= amt\n elif kind == 'bank_fee':\n adjusted_book -= amt\n else:\n raise ValueError('Unknown entry kind: {}'.format(kind))\n adj_bank_q = quant(adjusted_bank)\n adj_book_q = quant(adjusted_book)\n diff_q = quant(adj_bank_q - adj_book_q)\n return {\n 'adjusted_bank_balance': str(adj_bank_q),\n 'adjusted_book_balance': str(adj_book_q),\n 'difference': str(diff_q),\n }\n\nif __name__ == '__main__':\n result = reconcile_bank_statement(\n '1200.00', '1350.00',\n [('Payroll check 102', 'outstanding_check', '250.00'),\n ('Deposit 5/12', 'deposit_in_transit', '100.00'),\n ('Monthly fee', 'bank_fee', '12.50')]\n )\n print(result)\n assert result == {'adjusted_bank_balance': '1200.00',\n 'adjusted_book_balance': '1187.50',\n 'difference': '12.50'}"}], "meta": {"idx": 2380, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 726, "latency_s": 11.9}} +{"prompt": [{"role": "user", "content": "Your company keeps its books in USD but trades in multiple foreign currencies, and you must produce an FX gain/loss report from a transaction log. Purchases create foreign-currency liabilities recorded at the purchase-date FX rate; payments settle these liabilities FIFO across purchase lots, and each payment event produces a realized FX gain/loss in USD equal to settled_amount x (lot_rate - payment_rate), where a positive value is a gain because the liability was recorded at a higher rate than the payment cost. At period end, each remaining open lot carries an unrealized FX gain/loss equal to remaining_amount x (lot_rate - closing_rate), and the ending liability is valued at the closing rate. All monetary math must use Decimal, and every USD figure (per payment event, per open lot, and the ending liability) must be individually rounded to cents with ROUND_HALF_UP; totals are sums of these already-rounded figures. If a payment exceeds the open lots for that currency, raise ValueError. Implement fx_gain_loss_report(transactions, rates, closing_rates) where transactions is a list of (date, 'purchase'|'payment', currency, amount_string), rates maps currency -> {date: rate_string}, and closing_rates maps currency -> rate_string; it must return a dict with keys 'realized_events' (list of dicts with date, currency, amount, gain), 'total_realized_gain', 'unrealized_by_lot' (list of dicts with currency, amount, rate, gain), 'total_unrealized_gain', 'ending_liability' (dict currency -> FC amount and USD value), and 'total_fx_gain', all money values as strings formatted to two decimals. Worked example: rates EUR = {'2024-01-05':'1.10','2024-02-10':'1.08','2024-03-15':'1.05','2024-03-20':'1.04'}, closing_rates EUR = '1.02', transactions = [('2024-01-05','purchase','EUR','10000'), ('2024-02-10','purchase','EUR','5000'), ('2024-03-15','payment','EUR','8000'), ('2024-03-20','payment','EUR','3000')]. The 8000 payment settles lot 1 at 1.10 vs 1.05 for a 400.00 gain; the 3000 payment settles the remaining 2000 of lot 1 (gain 120.00) plus 1000 of lot 2 at 1.08 vs 1.04 (gain 40.00), event gain 160.00. Remaining open lot: 4000 EUR at 1.08, unrealized gain 4000x(1.08-1.02) = 240.00, ending liability 4000 EUR = 4080.00 USD, so the report shows total_realized_gain '560.00', total_unrealized_gain '240.00', and total_fx_gain '800.00'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import deque, defaultdict\n\nCENT = Decimal(\"0.01\")\n\n\ndef _q(value):\n \"\"\"Round a Decimal to cents using ROUND_HALF_UP.\"\"\"\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _fmt(value):\n \"\"\"Format a rounded Decimal money amount as a two-decimal string.\"\"\"\n return str(_q(value))\n\n\ndef fx_gain_loss_report(transactions, rates, closing_rates):\n \"\"\"Compute realized and unrealized FX gain/loss using FIFO lot settlement.\n\n transactions: list of (date, 'purchase'|'payment', currency, amount_str)\n rates: {currency: {date: rate_str}} (rate = FC units per 1 USD... no: USD per 1 FC)\n closing_rates: {currency: rate_str}\n\n Returns a report dict; all money values are two-decimal strings.\n \"\"\"\n # FIFO queues of open purchase lots per currency: [remaining_amount, lot_rate]\n lots = defaultdict(deque)\n\n # Parse rates into Decimals up front.\n dec_rates = {\n ccy: {date: Decimal(rate) for date, rate in table.items()}\n for ccy, table in rates.items()\n }\n dec_closing = {ccy: Decimal(rate) for ccy, rate in closing_rates.items()}\n\n realized_events = []\n total_realized = Decimal(\"0\")\n\n for date, kind, ccy, amount_str in transactions:\n amount = Decimal(amount_str)\n if amount <= 0:\n raise ValueError(\"transaction amounts must be positive\")\n try:\n rate = dec_rates[ccy][date]\n except KeyError:\n raise ValueError(\n \"missing FX rate for %s on %s\" % (ccy, date)\n )\n\n if kind == \"purchase\":\n lots[ccy].append([amount, rate])\n elif kind == \"payment\":\n remaining = amount\n event_gain = Decimal(\"0\")\n while remaining > 0:\n if not lots[ccy]:\n raise ValueError(\n \"payment of %s %s on %s exceeds open liability\"\n % (amount_str, ccy, date)\n )\n lot = lots[ccy][0]\n take = min(remaining, lot[0])\n # Liability recorded at lot_rate; paying costs payment_rate.\n # gain = settled_amount * (lot_rate - payment_rate)\n event_gain += take * (lot[1] - rate)\n lot[0] -= take\n remaining -= take\n if lot[0] == 0:\n lots[ccy].popleft()\n gain = _q(event_gain)\n total_realized += gain\n realized_events.append({\n \"date\": date,\n \"currency\": ccy,\n \"amount\": _fmt(amount),\n \"gain\": str(gain),\n })\n else:\n raise ValueError(\"unknown transaction kind: %r\" % (kind,))\n\n # Unrealized gain/loss on remaining open lots at closing rates.\n unrealized_by_lot = []\n total_unrealized = Decimal(\"0\")\n ending_liability = {}\n\n currencies = sorted(set(lots.keys()) | set(dec_closing.keys()))\n for ccy in currencies:\n if ccy not in dec_closing:\n raise ValueError(\"missing closing rate for %s\" % ccy)\n closing = dec_closing[ccy]\n fc_total = Decimal(\"0\")\n usd_total = Decimal(\"0\")\n for lot_amount, lot_rate in lots.get(ccy, deque()):\n gain = _q(lot_amount * (lot_rate - closing))\n usd_value = _q(lot_amount * closing)\n total_unrealized += gain\n fc_total += lot_amount\n usd_total += usd_value\n unrealized_by_lot.append({\n \"currency\": ccy,\n \"amount\": _fmt(lot_amount),\n \"rate\": str(lot_rate),\n \"gain\": str(gain),\n })\n ending_liability[ccy] = {\n \"fc_amount\": _fmt(fc_total),\n \"usd_value\": str(usd_total),\n }\n\n total_fx_gain = _q(total_realized + total_unrealized)\n\n return {\n \"realized_events\": realized_events,\n \"total_realized_gain\": str(total_realized),\n \"unrealized_by_lot\": unrealized_by_lot,\n \"total_unrealized_gain\": str(total_unrealized),\n \"ending_liability\": ending_liability,\n \"total_fx_gain\": str(total_fx_gain),\n }\n\n\nif __name__ == \"__main__\":\n rates = {\n \"EUR\": {\n \"2024-01-05\": \"1.10\",\n \"2024-02-10\": \"1.08\",\n \"2024-03-15\": \"1.05\",\n \"2024-03-20\": \"1.04\",\n }\n }\n closing_rates = {\"EUR\": \"1.02\"}\n transactions = [\n (\"2024-01-05\", \"purchase\", \"EUR\", \"10000\"),\n (\"2024-02-10\", \"purchase\", \"EUR\", \"5000\"),\n (\"2024-03-15\", \"payment\", \"EUR\", \"8000\"),\n (\"2024-03-20\", \"payment\", \"EUR\", \"3000\"),\n ]\n\n report = fx_gain_loss_report(transactions, rates, closing_rates)\n\n assert report[\"total_realized_gain\"] == \"560.00\", report\n assert report[\"total_unrealized_gain\"] == \"240.00\", report\n assert report[\"total_fx_gain\"] == \"800.00\", report\n assert report[\"ending_liability\"][\"EUR\"][\"fc_amount\"] == \"4000.00\"\n assert report[\"ending_liability\"][\"EUR\"][\"usd_value\"] == \"4080.00\"\n assert [e[\"gain\"] for e in report[\"realized_events\"]] == [\"400.00\", \"160.00\"]\n assert len(report[\"unrealized_by_lot\"]) == 1\n assert report[\"unrealized_by_lot\"][0][\"gain\"] == \"240.00\"\n\n # Overpayment must raise ValueError.\n try:\n fx_gain_loss_report(\n [(\"2024-01-05\", \"purchase\", \"EUR\", \"100\"),\n (\"2024-01-06\", \"payment\", \"EUR\", \"200\")],\n {\"EUR\": {\"2024-01-05\": \"1.10\", \"2024-01-06\": \"1.00\"}},\n {\"EUR\": \"1.00\"},\n )\n except ValueError:\n pass\n else:\n raise AssertionError(\"overpayment should raise ValueError\")\n\n print(\"All checks passed.\")\n print(report)"}], "meta": {"idx": 2371, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2119, "latency_s": 81.1}} +{"prompt": [{"role": "user", "content": "You are given a CSV file `transactions.csv` of bank transactions with columns: date (YYYY-MM-DD), description, amount (a decimal string, possibly with a leading '+' or '-'), and account (one of 'checking', 'savings'). Write a program that (1) validates each row: the date must parse as a real calendar date, the amount must be a valid decimal with at most 2 fractional digits, and the account must be one of the two allowed names; (2) skips invalid rows, writing them to `rejected.csv` with the original line and a reason column; (3) for valid rows, rounds each amount to 2 decimal places using Decimal and accumulates per-account totals and a running ledger balance in date order (stable within a day); and (4) writes valid rows sorted by date (stable) to `validated.csv` with an added running_balance column (2 decimal places), and prints a summary line for each account like `checking: 12.34` showing the net total. Monetary values must use Decimal throughout, never float. Example: input row `2023-01-05,Coffee,-3.50,checking` followed by `2023-01-05,Deposit,+100.00,checking` should produce validated rows with running balances `-3.50` and `96.50`, and summary `checking: 96.50`."}], "completion": [{"role": "assistant", "content": "import csv\nfrom datetime import datetime\nfrom decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\nACCOUNTS = {'checking', 'savings'}\n\n\ndef q(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef parse_amount(text):\n text = text.strip()\n if not text:\n return None, 'empty amount'\n try:\n amount = Decimal(text)\n except InvalidOperation:\n return None, 'invalid amount'\n if not amount.is_finite():\n return None, 'invalid amount'\n if -amount.as_tuple().exponent > 2:\n return None, 'more than 2 fractional digits'\n return q(amount), None\n\n\ndef parse_date(text):\n try:\n return datetime.strptime(text.strip(), '%Y-%m-%d').date()\n except ValueError:\n return None\n\n\ndef main(input_path='transactions.csv',\n valid_path='validated.csv',\n rejected_path='rejected.csv'):\n valid = []\n rejected = []\n with open(input_path, newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n reasons = []\n date = parse_date(row.get('date', ''))\n if date is None:\n reasons.append('bad date')\n amount, amt_err = parse_amount(row.get('amount', ''))\n if amt_err:\n reasons.append(amt_err)\n account = (row.get('account') or '').strip()\n if account not in ACCOUNTS:\n reasons.append('bad account')\n if reasons:\n rejected.append({\n 'date': row.get('date', ''),\n 'description': row.get('description', ''),\n 'amount': row.get('amount', ''),\n 'account': row.get('account', ''),\n 'reason': '; '.join(reasons),\n })\n else:\n valid.append({\n 'date': date,\n 'description': row.get('description', ''),\n 'amount': amount,\n 'account': account,\n })\n\n valid.sort(key=lambda r: r['date'])\n\n totals = {acct: Decimal('0.00') for acct in ACCOUNTS}\n balance = Decimal('0.00')\n out_rows = []\n for r in valid:\n balance += r['amount']\n totals[r['account']] += r['amount']\n out_rows.append({\n 'date': r['date'].isoformat(),\n 'description': r['description'],\n 'amount': f\"{q(r['amount']):.2f}\",\n 'account': r['account'],\n 'running_balance': f\"{q(balance):.2f}\",\n })\n\n fieldnames = ['date', 'description', 'amount', 'account', 'running_balance']\n with open(valid_path, 'w', newline='', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(out_rows)\n\n with open(rejected_path, 'w', newline='', encoding='utf-8') as f:\n writer = csv.DictWriter(\n f, fieldnames=['date', 'description', 'amount', 'account', 'reason'])\n writer.writeheader()\n writer.writerows(rejected)\n\n for acct in sorted(ACCOUNTS):\n print(f\"{acct}: {q(totals[acct]):.2f}\")\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2376, "topic": "transaction CSV import, validation, and export", "difficulty": "medium", "provider": "deepinfra", "in_tokens": 200, "out_tokens": 1159, "latency_s": 42.9}} +{"prompt": [{"role": "user", "content": "You are auditing a sales ledger for duplicate payments. Each transaction is recorded as a tuple (date, amount, description), where amount is a Decimal. A transaction is a 'suspected duplicate' if there exists an earlier transaction with the exact same amount AND the same description, and the date difference is at most 3 days. Additionally, flag any transaction as 'anomalous' if its amount is negative or exceeds Decimal('10000.00'). Write a function audit_ledger(transactions) that returns a list of result strings in the same order as the input: 'OK' for a clean transaction, 'DUPLICATE' for a suspected duplicate, and 'ANOMALOUS' for an amount that is negative or over 10000.00 (if a transaction is both a duplicate and anomalous, report 'ANOMALOUS'). Dates are ISO format strings; use datetime.date for comparison. Example: transactions = [('2024-01-02', Decimal('250.00'), 'ACME invoice'), ('2024-01-04', Decimal('250.00'), 'ACME invoice'), ('2024-01-20', Decimal('250.00'), 'ACME invoice'), ('2024-01-21', Decimal('15000.00'), 'Big sale')] should return ['OK', 'DUPLICATE', 'OK', 'ANOMALOUS'] because the second entry matches the first within 2 days, the third is too far away, and the fourth exceeds the 10000.00 limit."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom datetime import date\n\nLIMIT = Decimal('10000.00')\nWINDOW_DAYS = 3\n\ndef audit_ledger(transactions):\n results = []\n seen = {}\n for date_str, amount, description in transactions:\n d = date.fromisoformat(date_str)\n anomalous = amount < 0 or amount > LIMIT\n duplicate = False\n if not anomalous:\n for prev_date in seen.get((description, amount), []):\n if 0 <= (d - prev_date).days <= WINDOW_DAYS:\n duplicate = True\n break\n seen.setdefault((description, amount), []).append(d)\n if anomalous:\n results.append('ANOMALOUS')\n elif duplicate:\n results.append('DUPLICATE')\n else:\n results.append('OK')\n return results\n\nif __name__ == '__main__':\n txns = [\n ('2024-01-02', Decimal('250.00'), 'ACME invoice'),\n ('2024-01-04', Decimal('250.00'), 'ACME invoice'),\n ('2024-01-20', Decimal('250.00'), 'ACME invoice'),\n ('2024-01-21', Decimal('15000.00'), 'Big sale'),\n ]\n print(audit_ledger(txns))"}], "meta": {"idx": 2381, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 604, "latency_s": 6.6}} +{"prompt": [{"role": "user", "content": "You are maintaining a loan ledger for a small bookkeeping firm. A loan has a principal (a Decimal amount), a fixed annual nominal interest rate, and a list of monthly payments already recorded in the ledger. Interest is compounded monthly: at the end of each month, interest of (annual_rate / 12) is applied to the outstanding balance, rounded to the nearest cent using ROUND_HALF_UP, and then that month's payment (if any) is subtracted; the resulting balance is rounded to the nearest cent as well. If a payment exceeds the balance plus interest, the balance becomes zero (no negative balances are kept). Write a function `process_ledger(principal: str, annual_rate: str, payments: list[str]) -> list[str]` that returns a list of month-end balance strings, one per payment entry, each formatted with exactly two decimal places (e.g. '1234.56'). Use Decimal arithmetic throughout; do not use floats. Example: principal='1000.00', annual_rate='0.12', payments=['100.00','100.00','100.00'] gives monthly interest of 10.00 on 1000.00, so balances after each month are ['910.00','819.17','727.25'] (second month: 910.00 + 9.10 - 100.00 = 819.10? No: 910.00 interest is 9.10, giving 819.10 \u2014 verify carefully; the correct output is ['910.00','819.10','727.29'])."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef process_ledger(principal: str, annual_rate: str, payments: list[str]) -> list[str]:\n balance = Decimal(principal).quantize(TWO, rounding=ROUND_HALF_UP)\n monthly_rate = Decimal(annual_rate) / Decimal(12)\n balances = []\n for p in payments:\n interest = (balance * monthly_rate).quantize(TWO, rounding=ROUND_HALF_UP)\n balance = balance + interest - Decimal(p)\n if balance < 0:\n balance = Decimal('0.00')\n balance = balance.quantize(TWO, rounding=ROUND_HALF_UP)\n balances.append(str(balance))\n return balances\n\nif __name__ == '__main__':\n print(process_ledger('1000.00', '0.12', ['100.00', '100.00', '100.00']))\n print(process_ledger('500.00', '0.24', ['600.00', '0.00']))\n print(process_ledger('100.00', '0.05', ['10.00', '10.00', '95.00']))"}], "meta": {"idx": 2378, "topic": "interest calculation and payment schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 547, "latency_s": 65.2}} +{"prompt": [{"role": "user", "content": "A small business wants to automate its monthly rent expense posting. Write a function `post_rent(start_year, start_month, months, monthly_amount_cents, account='rent_expense')` that generates a list of ledger entries for the rent expense posted on the same day-of-month (the 1st) for `months` consecutive calendar months, starting from the given year and month. Each entry must be a dict with keys 'date' (string 'YYYY-MM-DD', always day 01), 'account' (the given account name), and 'amount_cents' (an int). Month arithmetic must correctly roll over years (e.g., month 13 becomes January of the next year). Return the list in chronological order. Example: `post_rent(2023, 11, 3, 120000)` returns `[{'date': '2023-11-01', 'account': 'rent_expense', 'amount_cents': 120000}, {'date': '2023-12-01', 'account': 'rent_expense', 'amount_cents': 120000}, {'date': '2024-01-01', 'account': 'rent_expense', 'amount_cents': 120000}]`. Use only the standard library."}], "completion": [{"role": "assistant", "content": "def post_rent(start_year, start_month, months, monthly_amount_cents, account='rent_expense'):\n entries = []\n year, month = start_year, start_month\n for _ in range(months):\n entries.append({\n 'date': f'{year:04d}-{month:02d}-01',\n 'account': account,\n 'amount_cents': int(monthly_amount_cents),\n })\n month += 1\n if month > 12:\n month = 1\n year += 1\n return entries\n\n\nif __name__ == '__main__':\n expected = [\n {'date': '2023-11-01', 'account': 'rent_expense', 'amount_cents': 120000},\n {'date': '2023-12-01', 'account': 'rent_expense', 'amount_cents': 120000},\n {'date': '2024-01-01', 'account': 'rent_expense', 'amount_cents': 120000},\n ]\n assert post_rent(2023, 11, 3, 120000) == expected\n assert post_rent(2024, 12, 2, 50000, 'office_rent') == [\n {'date': '2024-12-01', 'account': 'office_rent', 'amount_cents': 50000},\n {'date': '2025-01-01', 'account': 'office_rent', 'amount_cents': 50000},\n ]\n print('All tests passed.')"}], "meta": {"idx": 2385, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 523, "latency_s": 4.8}} +{"prompt": [{"role": "user", "content": "You are auditing a company's expense ledger. Each transaction is a tuple (date, amount, description), where amount is a string representing a monetary value (e.g., '250.00'). A transaction is a duplicate if an earlier transaction in the list has the same date, the same amount (compared as exact Decimal values, so '250.00' and '250.0' are equal), and the same description. A transaction is anomalous if its amount is negative and its absolute value is greater than 10000.00, or if it appears more than once per day (i.e., three or more transactions on the same calendar date, regardless of other fields). Write a function audit_ledger(transactions) that returns a list of report strings, one per flagged transaction, in the order the transactions appear in the input. Each report should be formatted as ' | DUPLICATE' for duplicates, ' | ANOMALY' for anomalies, or ' | DUPLICATE, ANOMALY' if both apply. Example: audit_ledger([('2024-01-05', '250.00', 'taxi'), ('2024-01-05', '250.0', 'taxi'), ('2024-01-06', '-15000.50', 'refund'), ('2024-01-06', '10.00', 'coffee'), ('2024-01-06', '12.00', 'lunch')]) returns ['2024-01-05 | DUPLICATE', '2024-01-06 | ANOMALY', '2024-01-06 | ANOMALY', '2024-01-06 | ANOMALY'] \u2014 the second taxi ride is a duplicate; the refund is an anomaly (negative amount > 10000 in absolute value); and since 2024-01-06 has three transactions, all of that day's transactions are flagged as anomalies."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom collections import Counter\n\n\ndef audit_ledger(transactions):\n seen = set()\n per_day = Counter(date for date, amount, description in transactions)\n reports = []\n for date, amount_str, description in transactions:\n amount = Decimal(amount_str)\n is_duplicate = (date, amount, description) in seen\n seen.add((date, amount, description))\n is_anomaly = (amount < 0 and abs(amount) > Decimal('10000.00')) or per_day[date] > 2\n flags = []\n if is_duplicate:\n flags.append('DUPLICATE')\n if is_anomaly:\n flags.append('ANOMALY')\n if flags:\n reports.append(date + ' | ' + ', '.join(flags))\n return reports\n\n\nif __name__ == '__main__':\n result = audit_ledger([\n ('2024-01-05', '250.00', 'taxi'),\n ('2024-01-05', '250.0', 'taxi'),\n ('2024-01-06', '-15000.50', 'refund'),\n ('2024-01-06', '10.00', 'coffee'),\n ('2024-01-06', '12.00', 'lunch'),\n ])\n expected = [\n '2024-01-05 | DUPLICATE',\n '2024-01-06 | ANOMALY',\n '2024-01-06 | ANOMALY',\n '2024-01-06 | ANOMALY',\n ]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2386, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 681, "latency_s": 6.5}} +{"prompt": [{"role": "user", "content": "You are given a company's cash ledger entries and a bank statement for the same period, and you must reconcile them. Each ledger entry is a tuple (date 'YYYY-MM-DD', type 'deposit' or 'withdrawal', amount as a string). The bank statement is a list of the same tuple shape. Due to bank processing delays, some ledger deposits appear on the bank statement 1-3 days later, and withdrawals may appear 1-3 days later as well; the amounts always match exactly. Additionally, the bank may have recorded service fees (type 'fee') that the company has not yet booked. Write a function reconcile(ledger, bank_statement) that returns a dictionary with: 'unmatched_ledger' (sorted list of ledger entries that never appear on the bank statement within the allowed delay window), 'unmatched_bank' (sorted list of bank entries not matched to any ledger entry, including fees), and 'adjusted_balance' (the bank balance adjusted for outstanding items, computed as Decimal). The adjusted balance equals the bank's net total (deposits minus withdrawals minus fees) plus outstanding withdrawals minus outstanding deposits, using Decimal arithmetic with two-decimal rounding. Example: ledger = [('2024-01-02','deposit','500.00'), ('2024-01-05','withdrawal','100.00')], bank = [('2024-01-03','deposit','500.00'), ('2024-01-08','withdrawal','100.00'), ('2024-01-10','fee','15.00')] should return unmatched_ledger = [], unmatched_bank = [('2024-01-10','fee','15.00')], and adjusted_balance = Decimal('385.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date, timedelta\n\n\ndef _parse(d):\n return date(*map(int, d.split('-')))\n\n\ndef reconcile(ledger, bank_statement):\n delay = timedelta(days=3)\n bank_used = [False] * len(bank_statement)\n unmatched_ledger = []\n\n for entry in ledger:\n l_date, l_type, l_amt = entry\n ld, amt = _parse(l_date), Decimal(l_amt)\n matched = False\n for i, b in enumerate(bank_statement):\n if bank_used[i] or b[1] != l_type:\n continue\n if b[2] != l_amt:\n continue\n bd = _parse(b[0])\n if ld <= bd <= ld + delay:\n bank_used[i] = True\n matched = True\n break\n if not matched:\n unmatched_ledger.append(entry)\n\n unmatched_bank = [b for i, b in enumerate(bank_statement) if not bank_used[i]]\n\n bank_net = Decimal('0')\n for _, t, a in bank_statement:\n amt = Decimal(a)\n if t == 'deposit':\n bank_net += amt\n else:\n bank_net -= amt\n\n outstanding_deposits = sum((Decimal(a) for _, t, a in unmatched_ledger if t == 'deposit'), Decimal('0'))\n outstanding_withdrawals = sum((Decimal(a) for _, t, a in unmatched_ledger if t == 'withdrawal'), Decimal('0'))\n\n adjusted = bank_net + outstanding_withdrawals - outstanding_deposits\n adjusted = adjusted.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n return {\n 'unmatched_ledger': sorted(unmatched_ledger),\n 'unmatched_bank': sorted(unmabk := unmatched_bank),\n 'adjusted_balance': adjusted,\n }\n\n\nif __name__ == '__main__':\n ledger = [('2024-01-02', 'deposit', '500.00'), ('2024-01-05', 'withdrawal', '100.00')]\n bank = [('2024-01-03', 'deposit', '500.00'), ('2024-01-08', 'withdrawal', '100.00'), ('2024-01-10', 'fee', '15.00')]\n result = reconcile(ledger, bank)\n print(result['unmatched_ledger'])\n print(result['unmatched_bank'])\n print(result['adjusted_balance'])"}], "meta": {"idx": 2382, "topic": "bank statement reconciliation", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 899, "latency_s": 25.3}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts as a list of tuples (code, name, parent_code) forming a tree (parent_code is None for roots), a list of journal entries, and a list of allocation rules. Each journal entry is a dict {'account': code, 'debit': Decimal} or {'account': code, 'credit': Decimal} with exactly one positive side and a non-negative amount, posted to an existing account. An allocation rule {'source': code, 'targets': [(code, weight), ...]} takes the current direct balance of the source account (postings made directly to it, excluding its children), credits the source for that full amount, and debits each target proportionally to its positive integer weight: each share is rounded half-up to cents, and any difference between the source amount and the sum of rounded shares is corrected one cent at a time to the targets in listed order (adding a cent when short, subtracting when over). Implement build_report(accounts, entries, allocations) that raises ValueError for unknown accounts or parents, parent cycles, non-positive total weights, a target equal to its source, a negative source balance, an entry with both or neither side positive, and a final trial balance where total debits do not equal total credits; otherwise it returns a dict mapping every account code to {'name', 'direct', 'total'}, where 'direct' is the account's own net debit-minus-credit balance after all allocations and 'total' is 'direct' plus the rolled-up totals of all descendants, both rounded half-up to cents. Worked example: with accounts [(1000,'Cash',None),(4000,'Expenses',None),(4100,'Office','4000'),(4110,'Supplies','4100'),(4120,'Rent','4100'),(4130,'Utilities','4100'),(4900,'Shared Pool','4000')], entries [{'account':'4110','debit':Decimal('25.00')},{'account':'1000','credit':Decimal('25.00')},{'account':'4900','debit':Decimal('10.00')},{'account':'1000','credit':Decimal('10.00')}], and allocation {'source':'4900','targets':[('4110',1),('4120',1),('4130',1)]}, the report must give 4110 direct 28.34 (25.00 plus 3.34, the extra cent from the 9.99 vs 10.00 rounding shortfall), 4120 and 4130 direct 3.33 each, 4900 direct 0.00, 4100 total 35.00, 4000 total 35.00, and 1000 total -35.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0\")\n\n\ndef _q2(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef build_report(accounts, entries, allocations):\n names = {}\n parent = {}\n children = {}\n roots = []\n for code, name, par in accounts:\n if code in names:\n raise ValueError(\"duplicate account code: %r\" % (code,))\n names[code] = name\n parent[code] = par\n children.setdefault(code, [])\n if par is None:\n roots.append(code)\n else:\n children.setdefault(par, []).append(code)\n for code, par in parent.items():\n if par is not None and par not in names:\n raise ValueError(\"unknown parent %r for account %r\" % (par, code))\n for code in names:\n seen = set()\n cur = code\n while cur is not None:\n if cur in seen:\n raise ValueError(\"parent cycle involving %r\" % (cur,))\n seen.add(cur)\n cur = parent[cur]\n\n debits = dict.fromkeys(names, ZERO)\n credits = dict.fromkeys(names, ZERO)\n total_dr = ZERO\n total_cr = ZERO\n\n for e in entries:\n acct = e[\"account\"]\n if acct not in names:\n raise ValueError(\"unknown account %r in entry\" % (acct,))\n d = e.get(\"debit\", ZERO)\n c = e.get(\"credit\", ZERO)\n if not isinstance(d, Decimal) or not isinstance(c, Decimal):\n raise ValueError(\"amounts must be Decimal\")\n if d < ZERO or c < ZERO:\n raise ValueError(\"entry amounts must be non-negative\")\n if (d > ZERO) == (c > ZERO):\n raise ValueError(\"entry must have exactly one positive side\")\n debits[acct] += d\n credits[acct] += c\n total_dr += d\n total_cr += c\n\n for alloc in allocations:\n src = alloc[\"source\"]\n if src not in names:\n raise ValueError(\"unknown source account %r\" % (src,))\n targets = alloc[\"targets\"]\n for tgt, w in targets:\n if tgt not in names:\n raise ValueError(\"unknown target account %r\" % (tgt,))\n if tgt == src:\n raise ValueError(\"allocation target %r equals source\" % (tgt,))\n if w <= 0:\n raise ValueError(\"allocation weights must be positive\")\n wsum = sum(w for _, w in targets)\n if wsum <= 0:\n raise ValueError(\"total allocation weight must be positive\")\n amt = debits[src] - credits[src]\n if amt < ZERO:\n raise ValueError(\"source account %r has a negative balance\" % (src,))\n if amt == ZERO:\n continue\n credits[src] += amt\n total_cr += amt\n shares = []\n distributed = ZERO\n for tgt, w in targets:\n s = _q2(amt * Decimal(w) / Decimal(wsum))\n shares.append([tgt, s])\n distributed += s\n diff = amt - distributed\n i = 0\n while diff != ZERO:\n step = CENT if diff > ZERO else -CENT\n shares[i % len(shares)][1] += step\n diff -= step\n i += 1\n for tgt, s in shares:\n debits[tgt] += s\n total_dr += s\n\n if total_dr != total_cr:\n raise ValueError(\n \"trial balance failed: debits %s != credits %s\" % (total_dr, total_cr)\n )\n\n direct = {code: debits[code] - credits[code] for code in names}\n total = {}\n\n def calc(code):\n t = direct[code] + sum(calc(ch) for ch in children[code])\n total[code] = t\n return t\n\n for r in roots:\n calc(r)\n\n return {\n code: {\n \"name\": names[code],\n \"direct\": _q2(direct[code]),\n \"total\": _q2(total[code]),\n }\n for code in names\n }\n\n\nif __name__ == \"__main__\":\n accounts = [\n (\"1000\", \"Cash\", None),\n (\"4000\", \"Expenses\", None),\n (\"4100\", \"Office\", \"4000\"),\n (\"4110\", \"Supplies\", \"4100\"),\n (\"4120\", \"Rent\", \"4100\"),\n (\"4130\", \"Utilities\", \"4100\"),\n (\"4900\", \"Shared Pool\", \"4000\"),\n ]\n entries = [\n {\"account\": \"4110\", \"debit\": Decimal(\"25.00\")},\n {\"account\": \"1000\", \"credit\": Decimal(\"25.00\")},\n {\"account\": \"4900\", \"debit\": Decimal(\"10.00\")},\n {\"account\": \"1000\", \"credit\": Decimal(\"10.00\")},\n ]\n allocations = [\n {\"source\": \"4900\", \"targets\": [(\"4110\", 1), (\"4120\", 1), (\"4130\", 1)]}\n ]\n report = build_report(accounts, entries, allocations)\n for code in sorted(report):\n row = report[code]\n print(code, row[\"name\"], \"direct=\", row[\"direct\"], \"total=\", row[\"total\"])\n assert report[\"4110\"][\"direct\"] == Decimal(\"28.34\")\n assert report[\"4120\"][\"direct\"] == Decimal(\"3.33\")\n assert report[\"4130\"][\"direct\"] == Decimal(\"3.33\")\n assert report[\"4900\"][\"direct\"] == Decimal(\"0.00\")\n assert report[\"4100\"][\"total\"] == Decimal(\"35.00\")\n assert report[\"4000\"][\"total\"] == Decimal(\"35.00\")\n assert report[\"1000\"][\"total\"] == Decimal(\"-35.00\")\n print(\"all checks passed\")"}], "meta": {"idx": 2364, "topic": "chart of accounts and expense categorization", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1912, "latency_s": 123.2}} +{"prompt": [{"role": "user", "content": "You are maintaining a simple chart of accounts for a small business. Each account has a code, a name, and a type ('income', 'expense', 'asset', or 'liability'). Write a function `categorize_expenses(accounts, entries)` that takes a list of accounts, where each account is a tuple `(code, name, type)`, and a list of entries, where each entry is a tuple `(account_code, amount)` with the amount given as a string (to be parsed with `Decimal`). Return a dictionary mapping each expense account name to the total of all amounts posted to that account, rounded to 2 decimal places using ROUND_HALF_UP. Amounts posted to accounts that are not of type 'expense', or to unknown account codes, must be ignored. If an expense account receives no valid entries, it should still appear in the result with a total of Decimal('0.00'). Example: accounts = [('4001', 'Office Supplies', 'expense'), ('4002', 'Rent', 'expense'), ('5001', 'Sales Revenue', 'income')], entries = [('4001', '12.345'), ('4002', '100'), ('4001', '7.655'), ('5001', '500'), ('9999', '10')] should return {'Office Supplies': Decimal('20.00'), 'Rent': Decimal('100.00')} because 12.345 + 7.655 = 20.000 rounds to 20.00 and income/unknown accounts are ignored."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef categorize_expenses(accounts, entries):\n expense_names = {}\n for code, name, acct_type in accounts:\n if acct_type == 'expense':\n expense_names[code] = name\n\n totals = {name: Decimal('0') for name in expense_names.values()}\n\n for code, amount in entries:\n if code in expense_names:\n totals[expense_names[code]] += Decimal(amount)\n\n result = {}\n for name, total in totals.items():\n result[name] = total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return result\n\n\nif __name__ == '__main__':\n accounts = [('4001', 'Office Supplies', 'expense'),\n ('4002', 'Rent', 'expense'),\n ('5001', 'Sales Revenue', 'income')]\n entries = [('4001', '12.345'), ('4002', '100'), ('4001', '7.655'),\n ('5001', '500'), ('9999', '10')]\n print(categorize_expenses(accounts, entries))"}], "meta": {"idx": 2384, "topic": "chart of accounts and expense categorization", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 551, "latency_s": 21.1}} +{"prompt": [{"role": "user", "content": "A petty cash fund starts with a fixed imprest amount (e.g. $200.00). Disbursements are recorded as entries, each with a description and a Decimal amount. When the cash on hand plus recorded receipts falls below 20% of the imprest amount, the fund must be replenished back to the imprest level. Write a function `process_petty_cash(imprest, entries)` that takes the imprest amount (Decimal or string) and a list of (description, amount) tuples, applies disbursements in order, and returns a dict with: 'total_disbursed' (sum of all amounts, quantized to cents), 'cash_on_hand' (imprest minus total disbursed, never below zero \u2014 if a disbursement would exceed cash on hand, it is recorded but flagged), 'replenishments' (list of replenishment amounts), and 'flagged' (list of descriptions of disbursements that could not be fully covered). Replenishment is triggered immediately after any disbursement that brings cash on hand (before replenishment) below 20% of imprest; the replenishment restores cash on hand to exactly the imprest amount. Round all money values to 2 decimal places using ROUND_HALF_UP. Example: imprest=200.00, entries=[('taxi', '45.00'), ('snacks', '12.50'), ('stamps', '110.00')] \u2192 after 'taxi' cash=155.00 (>=40, ok), after 'snacks' cash=142.50 (ok), after 'stamps' cash=32.50 (<40) so replenish 167.50 \u2192 {'total_disbursed': Decimal('167.50'), 'cash_on_hand': Decimal('200.00'), 'replenishments': [Decimal('167.50')], 'flagged': []}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef process_petty_cash(imprest, entries):\n TWO = Decimal('0.01')\n imprest = Decimal(str(imprest)).quantize(TWO, rounding=ROUND_HALF_UP)\n threshold = (imprest * Decimal('0.20')).quantize(TWO, rounding=ROUND_HALF_UP)\n\n total = Decimal('0.00')\n cash = imprest\n replenishments = []\n flagged = []\n\n for description, amount in entries:\n amt = Decimal(str(amount)).quantize(TWO, rounding=ROUND_HALF_UP)\n total += amt\n if amt > cash:\n flagged.append(description)\n cash = Decimal('0.00')\n else:\n cash -= amt\n if cash < threshold:\n replen = (imprest - cash).quantize(TWO, rounding=ROUND_HALF_UP)\n replenishments.append(replen)\n cash = imprest\n\n return {\n 'total_disbursed': total.quantize(TWO, rounding=ROUND_HALF_UP),\n 'cash_on_hand': cash.quantize(TWO, rounding=ROUND_HALF_UP),\n 'replenishments': replenishments,\n 'flagged': flagged,\n }\n\n\nif __name__ == '__main__':\n result = process_petty_cash('200.00', [('taxi', '45.00'), ('snacks', '12.50'), ('stamps', '110.00')])\n print(result)"}], "meta": {"idx": 2379, "topic": "petty cash logs and replenishment", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 677, "latency_s": 54.1}} +{"prompt": [{"role": "user", "content": "A petty cash fund starts with a fixed imprest amount (e.g., $300.00). Each voucher records an expense category and an amount. Write a function `petty_cash_report(vouchers, imprest)` that takes a list of (category, amount) tuples (amounts as strings) and the imprest amount as a string, and returns a dict with: 'total_expenses' (Decimal, sum of all vouchers), 'cash_on_hand' (Decimal, imprest minus total expenses), 'replenishment' (Decimal, the amount needed to restore the fund to imprest, equal to total expenses), and 'by_category' (a dict mapping category to its Decimal total, with each category total rounded to 2 decimal places using ROUND_HALF_UP). All monetary values must use Decimal with ROUND_HALF_UP to 2 decimals. If cash_on_hand would be negative, raise ValueError. Example: vouchers = [('office supplies', '12.49'), ('postage', '5.50'), ('office supplies', '3.01')], imprest = '100.00' gives total_expenses = Decimal('21.00'), cash_on_hand = Decimal('79.00'), replenishment = Decimal('21.00'), and by_category = {'office supplies': Decimal('15.50'), 'postage': Decimal('5.50')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef petty_cash_report(vouchers, imprest):\n def money(value):\n return Decimal(value).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n imprest_d = money(imprest)\n by_category = {}\n total = Decimal('0.00')\n for category, amount in vouchers:\n amt = money(amount)\n total += amt\n by_category[category] = by_category.get(category, Decimal('0.00')) + amt\n\n by_category = {cat: money(val) for cat, val in by_category.items()}\n total = money(total)\n cash_on_hand = money(imprest_d - total)\n if cash_on_hand < 0:\n raise ValueError('Petty cash fund overdrawn: expenses exceed imprest amount')\n\n return {\n 'total_expenses': total,\n 'cash_on_hand': cash_on_hand,\n 'replenishment': total,\n 'by_category': by_category,\n }\n\n\nif __name__ == '__main__':\n vouchers = [('office supplies', '12.49'), ('postage', '5.50'), ('office supplies', '3.01')]\n result = petty_cash_report(vouchers, '100.00')\n print(result)"}], "meta": {"idx": 2388, "topic": "petty cash logs and replenishment", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 552, "latency_s": 7.4}} +{"prompt": [{"role": "user", "content": "You are closing the books for a small business at period end. You are given a list of general ledger accounts, each represented as a tuple (account_name, account_type, balance) where account_type is one of 'revenue', 'expense', 'asset', 'liability', or 'equity', and balance is a Decimal where positive means a debit balance and negative means a credit balance. Write a function `period_end_close(accounts, rounding=ROUND_HALF_UP)` that performs the standard closing routine: (1) close all revenue and expense accounts into an 'Income Summary' account, (2) compute net income (revenues minus expenses; credit balances of revenue accounts are revenues), (3) close Income Summary into an equity account named 'Retained Earnings' (creating it if absent), and (4) return a dict mapping each surviving account name (all asset, liability, and equity accounts, plus 'Retained Earnings') to its post-closing balance as a Decimal rounded to 2 places using the given rounding mode. Revenue and expense accounts must not appear in the result. For example, accounts = [('Sales','revenue',Decimal('-1200.50')),('Rent','expense',Decimal('400.25')),('Cash','asset',Decimal('5000.00')),('Payables','liability',Decimal('-300.00'))] should return {'Cash': Decimal('5000.00'), 'Payables': Decimal('-300.00'), 'Retained Earnings': Decimal('800.25')} because net income = 1200.50 - 400.25 = 800.25 is credited (negative) to Retained Earnings... wait, here report the post-closing balance as net income with a credit sign convention: Retained Earnings = -(net income) = -800.25? No\u2014use the convention that the returned Retained Earnings balance equals the net income amount as a positive Decimal when income is positive: {'Cash': Decimal('5000.00'), 'Payables': Decimal('-300.00'), 'Retained Earnings': Decimal('800.25')}. If an existing 'Retained Earnings' equity account is present, add the net income to its existing credit balance expressed as a positive amount (i.e., new_retained = old_positive_equity + net_income)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef period_end_close(accounts, rounding=ROUND_HALF_UP):\n net_income = Decimal('0')\n result = {}\n existing_retained = Decimal('0')\n for name, atype, balance in accounts:\n balance = Decimal(balance)\n if atype == 'revenue':\n # credit balance (negative) is revenue\n net_income += -balance\n elif atype == 'expense':\n # debit balance (positive) is expense\n net_income -= balance\n elif atype in ('asset', 'liability'):\n result[name] = balance\n elif atype == 'equity':\n if name == 'Retained Earnings':\n existing_retained = -balance # credit balance as positive\n else:\n result[name] = balance\n result['Retained Earnings'] = existing_retained + net_income\n q = Decimal('0.01')\n return {name: bal.quantize(q, rounding=rounding) for name, bal in result.items()}\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n accounts = [('Sales', 'revenue', Decimal('-1200.50')),\n ('Rent', 'expense', Decimal('400.25')),\n ('Cash', 'asset', Decimal('5000.00')),\n ('Payables', 'liability', Decimal('-300.00'))]\n print(period_end_close(accounts))"}], "meta": {"idx": 2387, "topic": "period-end closing entries and routines", "difficulty": "medium", "provider": "novita", "in_tokens": 198, "out_tokens": 830, "latency_s": 10.3}} +{"prompt": [{"role": "user", "content": "You are building the inventory-valuation engine for a small-business bookkeeping system. Given a chronological list of transactions, where each transaction is a tuple ('BUY', qty, unit_cost) for a purchase or ('SELL', qty, None) for a sale (quantities are positive integers, unit costs are decimal money amounts), write a function value_inventory(transactions, method) that computes, under the given method ('FIFO', 'LIFO', or 'WA' for moving weighted average), the cost of goods sold for each sale rounded to cents with ROUND_HALF_UP, the total COGS, and the ending inventory value. All money arithmetic must use Decimal; the ending inventory value must be computed as (total cost of all purchases) minus (sum of the per-sale rounded COGS figures), so the accounting identity 'purchases cost = total COGS + ending inventory' holds exactly to the cent. The function must raise ValueError if a quantity is non-positive, a unit cost is non-positive, the method is invalid, or a sale exceeds the units currently on hand. Worked example: transactions = [('BUY', 10, '2.00'), ('BUY', 20, '3.00'), ('SELL', 15, None)] \u2014 under FIFO the single sale has COGS 35.00 (10 x 2.00 + 5 x 3.00) and ending inventory 45.00; under LIFO COGS is 45.00 (15 x 3.00) and ending inventory 35.00; under WA the average cost after both purchases is 80.00/30 = 2.6667 per unit, so COGS is 40.00 and ending inventory is 40.00. The function should return a dict like {'method': 'FIFO', 'cogs_by_sale': [Decimal('35.00')], 'total_cogs': Decimal('35.00'), 'ending_inventory': Decimal('45.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import deque\n\nCENT = Decimal(\"0.01\")\n\n\ndef _money(value):\n \"\"\"Round a Decimal to cents using half-up rounding.\"\"\"\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef value_inventory(transactions, method):\n \"\"\"Value inventory and COGS under FIFO, LIFO, or moving weighted average.\n\n transactions: iterable of ('BUY', qty, unit_cost) or ('SELL', qty, None)\n method: 'FIFO', 'LIFO', or 'WA'\n\n Returns dict with keys: method, cogs_by_sale, total_cogs, ending_inventory.\n Ending inventory is the residual of total purchase cost minus total\n (rounded) COGS, so purchases = COGS + ending inventory holds exactly.\n \"\"\"\n if method not in (\"FIFO\", \"LIFO\", \"WA\"):\n raise ValueError(\"method must be 'FIFO', 'LIFO', or 'WA'\")\n\n fifo_layers = deque() # each layer: [qty, unit_cost], oldest at left\n lifo_layers = deque() # same layers, consumed from the right\n pool_qty = 0 # units on hand for weighted-average pool\n pool_cost = Decimal(\"0\") # exact (unrounded) cost of units on hand\n total_purchase_cost = Decimal(\"0\")\n cogs_by_sale = []\n\n for entry in transactions:\n if len(entry) != 3:\n raise ValueError(\"each transaction must be a 3-tuple\")\n kind, qty, price = entry\n qty = int(qty)\n if qty <= 0:\n raise ValueError(\"quantity must be a positive integer\")\n\n if kind == \"BUY\":\n unit_cost = Decimal(str(price))\n if unit_cost <= 0:\n raise ValueError(\"unit cost must be positive\")\n fifo_layers.append([qty, unit_cost])\n lifo_layers.append([qty, unit_cost])\n pool_qty += qty\n pool_cost += unit_cost * qty\n total_purchase_cost += unit_cost * qty\n\n elif kind == \"SELL\":\n if qty > pool_qty:\n raise ValueError(\n \"cannot sell %d units; only %d on hand\" % (qty, pool_qty)\n )\n\n if method == \"FIFO\":\n remaining = qty\n cogs_exact = Decimal(\"0\")\n while remaining > 0:\n layer = fifo_layers[0]\n take = min(remaining, layer[0])\n cogs_exact += take * layer[1]\n layer[0] -= take\n remaining -= take\n if layer[0] == 0:\n fifo_layers.popleft()\n\n elif method == \"LIFO\":\n remaining = qty\n cogs_exact = Decimal(\"0\")\n while remaining > 0:\n layer = lifo_layers[-1]\n take = min(remaining, layer[0])\n cogs_exact += take * layer[1]\n layer[0] -= take\n remaining -= take\n if layer[0] == 0:\n lifo_layers.pop()\n\n else: # WA: moving weighted average\n avg_cost = pool_cost / pool_qty\n cogs_exact = avg_cost * qty\n\n # Reduce the weighted-average pool by the exact COGS.\n pool_qty -= qty\n pool_cost -= cogs_exact\n cogs_by_sale.append(_money(cogs_exact))\n\n else:\n raise ValueError(\"transaction kind must be 'BUY' or 'SELL'\")\n\n total_cogs = sum(cogs_by_sale, Decimal(\"0\"))\n ending_inventory = total_purchase_cost - total_cogs\n\n return {\n \"method\": method,\n \"cogs_by_sale\": cogs_by_sale,\n \"total_cogs\": _money(total_cogs),\n \"ending_inventory\": _money(ending_inventory),\n }\n\n\nif __name__ == \"__main__\":\n txns = [\n (\"BUY\", 10, \"2.00\"),\n (\"BUY\", 20, \"3.00\"),\n (\"SELL\", 15, None),\n ]\n for m in (\"FIFO\", \"LIFO\", \"WA\"):\n result = value_inventory(txns, m)\n print(m, result)\n # FIFO: cogs_by_sale=[35.00], total_cogs=35.00, ending_inventory=45.00\n # LIFO: cogs_by_sale=[45.00], total_cogs=45.00, ending_inventory=35.00\n # WA: cogs_by_sale=[40.00], total_cogs=40.00, ending_inventory=40.00"}], "meta": {"idx": 2368, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1462, "latency_s": 125.0}} +{"prompt": [{"role": "user", "content": "A bookkeeper needs a depreciation schedule generator. Write a function `depreciation_schedule(cost, salvage, life, method)` where `cost` and `salvage` are strings representing monetary amounts (e.g. '12000.00'), `life` is a positive integer number of years, and `method` is either 'straight-line' or 'declining-balance'. Use `Decimal` with two-decimal quantization (ROUND_HALF_UP) for all money values. For 'straight-line', each year's depreciation is `(cost - salvage) / life`, with any final-year adjustment so the accumulated depreciation exactly equals `cost - salvage`. For 'declining-balance', the annual rate is `2 / life` (double-declining balance), each year's depreciation is `rate * remaining_book_value`, depreciation stops when the book value would drop below salvage, and the final year's depreciation is capped so the ending book value equals salvage exactly (if cost > salvage). The function returns a list of tuples `(year, depreciation_expense, accumulated_depreciation, book_value)`, all amounts as Decimal quantized to 2 places, with years numbered from 1. Example: cost='10000.00', salvage='1000.00', life=5, method='declining-balance' gives year 1 depreciation 4000.00, accumulated 4000.00, book value 6000.00; year 2 depreciation 2400.00, accumulated 6400.00, book value 3600.00; year 5 depreciation 440.00, accumulated 9000.00, book value 1000.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef q(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef depreciation_schedule(cost, salvage, life, method):\n cost = q(Decimal(cost))\n salvage = q(Decimal(salvage))\n rate = Decimal(2) / Decimal(life)\n schedule = []\n acc = Decimal('0.00')\n bv = cost\n\n if method == 'straight-line':\n total = cost - salvage\n base = q(total / Decimal(life))\n for year in range(1, life + 1):\n if year < life:\n dep = base\n else:\n dep = q(total - acc)\n acc = q(acc + dep)\n bv = q(cost - acc)\n schedule.append((year, q(dep), acc, bv))\n elif method == 'declining-balance':\n for year in range(1, life + 1):\n dep = q(rate * bv)\n if q(bv - dep) < salvage:\n dep = q(bv - salvage)\n if dep <= 0:\n dep = Decimal('0.00')\n acc = q(acc + dep)\n bv = q(cost - acc)\n schedule.append((year, q(dep), acc, bv))\n else:\n raise ValueError(\"method must be 'straight-line' or 'declining-balance'\")\n\n return schedule\n\n\nif __name__ == '__main__':\n for row in depreciation_schedule('10000.00', '1000.00', 5, 'declining-balance'):\n print(row)\n for row in depreciation_schedule('10000.00', '1000.00', 5, 'straight-line'):\n print(row)"}], "meta": {"idx": 2390, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 721, "latency_s": 7.5}} +{"prompt": [{"role": "user", "content": "Implement a mini double-entry bookkeeping system. A journal entry is a dict with an 'id' and a list of (account, debit, credit) lines using Decimal amounts. Write a function `post_entries(entries)` that validates and posts entries to a general ledger and returns a trial balance. Validation rules: (1) each entry must have at least two lines; (2) total debits must equal total credits exactly (no rounding tolerance); (3) each line's debit and credit must be non-negative Decimals and at most one of debit/credit per line may be non-zero. An invalid entry must raise a ValueError containing the entry id and must not affect the ledger. For valid entries, post each line to its account: debits increase the account's debit total, credits increase the credit total. The returned trial balance is a dict mapping each account name to its net balance (debits minus credits) as a Decimal, plus compute total debits and total credits across all accounts to confirm the trial balance balances. Example: entries = [{'id': 'E1', 'lines': [('Cash', Decimal('100.00'), Decimal('0')), ('Revenue', Decimal('0'), Decimal('100.00'))]}, {'id': 'E2', 'lines': [('Rent Expense', Decimal('50.00'), Decimal('0')), ('Cash', Decimal('0'), Decimal('50.00'))]}] should yield trial balance {'Cash': Decimal('50.00'), 'Revenue': Decimal('-100.00'), 'Rent Expense': Decimal('50.00')} with total debits = total credits = Decimal('150.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef post_entries(entries):\n \"\"\"Validate and post journal entries; return trial balance.\n\n Returns a dict with:\n 'accounts': {account_name: net Decimal balance (debits - credits)}\n 'total_debits': Decimal sum of all posted debits\n 'total_credits': Decimal sum of all posted credits\n \"\"\"\n ledger = {} # account -> {'debits': Decimal, 'credits': Decimal}\n\n for entry in entries:\n entry_id = entry.get('id', '')\n lines = entry.get('lines', [])\n\n if len(lines) < 2:\n raise ValueError(\n f\"Entry {entry_id}: must have at least two lines\")\n\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for account, debit, credit in lines:\n debit = debit if isinstance(debit, Decimal) else Decimal(str(debit))\n credit = credit if isinstance(credit, Decimal) else Decimal(str(credit))\n if debit < 0 or credit < 0:\n raise ValueError(\n f\"Entry {entry_id}: negative amount not allowed\")\n if debit != 0 and credit != 0:\n raise ValueError(\n f\"Entry {entry_id}: line cannot have both debit and credit\")\n total_debits += debit\n total_credits += credit\n\n if total_debits != total_credits:\n raise ValueError(\n f\"Entry {entry_id}: unbalanced (debits={total_debits}, \"\n f\"credits={total_credits})\")\n\n # Entry is valid: post it.\n for account, debit, credit in lines:\n debit = debit if isinstance(debit, Decimal) else Decimal(str(debit))\n credit = credit if isinstance(credit, Decimal) else Decimal(str(credit))\n acct = ledger.setdefault(account,\n {'debits': Decimal('0'),\n 'credits': Decimal('0')})\n acct['debits'] += debit\n acct['credits'] += credit\n\n trial_balance = {\n account: data['debits'] - data['credits']\n for account, data in ledger.items()\n }\n total_debits = sum((d['debits'] for d in ledger.values()), Decimal('0'))\n total_credits = sum((d['credits'] for d in ledger.values()), Decimal('0'))\n\n return {\n 'accounts': trial_balance,\n 'total_debits': total_debits,\n 'total_credits': total_credits,\n }\n\n\nif __name__ == '__main__':\n entries = [\n {'id': 'E1', 'lines': [\n ('Cash', Decimal('100.00'), Decimal('0')),\n ('Revenue', Decimal('0'), Decimal('100.00'))]},\n {'id': 'E2', 'lines': [\n ('Rent Expense', Decimal('50.00'), Decimal('0')),\n ('Cash', Decimal('0'), Decimal('50.00'))]},\n ]\n result = post_entries(entries)\n assert result['accounts'] == {\n 'Cash': Decimal('50.00'),\n 'Revenue': Decimal('-100.00'),\n 'Rent Expense': Decimal('50.00')}\n assert result['total_debits'] == Decimal('150.00')\n assert result['total_credits'] == Decimal('150.00')\n\n # Invalid entry: unbalanced, must raise and not affect ledger.\n try:\n post_entries([{'id': 'BAD', 'lines': [\n ('Cash', Decimal('10'), Decimal('0')),\n ('Revenue', Decimal('0'), Decimal('9'))]}])\n assert False, 'should have raised'\n except ValueError as e:\n assert 'BAD' in str(e)\n\n print('All checks passed.')"}], "meta": {"idx": 2389, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1244, "latency_s": 15.7}} +{"prompt": [{"role": "user", "content": "A petty cash fund starts with a fixed imprest amount and is replenished back to that amount at the end of each week. You are given the opening float and a list of weekly expense records, where each record is a tuple (week_label, list_of_expense_strings) and each expense string is a decimal amount like '12.34' representing money paid out of the fund. Write a function petty_cash_report(float_amount, weeks) that returns a list of strings, one per week, each formatted exactly as: ' spent=X.XX replenish=Y.XX', where X.XX is the total spent that week and Y.YX... that is, Y.YY is the replenishment needed to restore the fund to the imprest amount. Replenishment equals total spent (assume the cash on hand plus receipts always reconcile). Use Decimal for all money arithmetic and quantize to 2 decimal places with ROUND_HALF_UP. Example: float_amount='100.00', weeks=[('W1', ['10.00','2.50']), ('W2', ['5.25'])] returns ['W1 spent=12.50 replenish=12.50', 'W2 spent=5.25 replenish=5.25']."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef petty_cash_report(float_amount, weeks):\n imprest = Decimal(float_amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n two_places = Decimal('0.01')\n lines = []\n for week_label, expenses in weeks:\n spent = Decimal('0.00')\n for amount in expenses:\n spent += Decimal(amount)\n spent = spent.quantize(two_places, rounding=ROUND_HALF_UP)\n replenish = spent.quantize(two_places, rounding=ROUND_HALF_UP)\n lines.append('{} spent={} replenish={}'.format(\n week_label,\n spent,\n replenish,\n ))\n return lines\n\n\nif __name__ == '__main__':\n result = petty_cash_report('100.00', [('W1', ['10.00', '2.50']), ('W2', ['5.25'])])\n print(result)\n assert result == ['W1 spent=12.50 replenish=12.50', 'W2 spent=5.25 replenish=5.25']"}], "meta": {"idx": 2393, "topic": "petty cash logs and replenishment", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 482, "latency_s": 8.5}} +{"prompt": [{"role": "user", "content": "Write a program that processes a JSON-encoded invoice ledger and produces a VAT report with correct Decimal rounding. Input is a JSON object mapping invoice IDs to lists of line items, where each line item is an object with 'net' (string, e.g. \"100.00\"), 'qty' (integer), and 'vat_rate' (string percentage, e.g. \"19.00\"). For each invoice, compute each line total as net * qty, the VAT amount per line rounded half-up to 2 decimal places, and the gross total. Then output a JSON report listing per invoice: net total, vat total, gross total, and a grand total across all invoices, all as strings with exactly 2 decimals. All arithmetic must use Decimal to avoid floating-point errors. Example: invoice 'A1' with line {\"net\": \"10.05\", \"qty\": 3, \"vat_rate\": \"19.00\"} has line total 30.15, VAT = 30.15 * 0.19 = 5.7285 which rounds half-up to 5.73, so net=\"30.15\", vat=\"5.73\", gross=\"35.88\"."}], "completion": [{"role": "assistant", "content": "import json\nfrom decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal(\"0.01\")\n\n\ndef r2(d: Decimal) -> Decimal:\n return d.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef fmt(d: Decimal) -> str:\n return str(r2(d).quantize(TWO))\n\n\ndef build_report(ledger: dict) -> dict:\n grand_net = Decimal(\"0\")\n grand_vat = Decimal(\"0\")\n grand_gross = Decimal(\"0\")\n invoices = {}\n for inv_id, lines in ledger.items():\n net_total = Decimal(\"0\")\n vat_total = Decimal(\"0\")\n for line in lines:\n net = Decimal(line[\"net\"])\n qty = Decimal(line[\"qty\"])\n rate = Decimal(line[\"vat_rate\"])\n line_net = net * qty\n vat = r2(line_net * (rate / Decimal(\"100\")))\n net_total += line_net\n vat_total += vat\n gross_total = net_total + vat_total\n invoices[inv_id] = {\n \"net\": fmt(net_total),\n \"vat\": fmt(vat_total),\n \"gross\": fmt(gross_total),\n }\n grand_net += net_total\n grand_vat += vat_total\n grand_gross += gross_total\n return {\n \"invoices\": invoices,\n \"grand_total\": {\n \"net\": fmt(grand_net),\n \"vat\": fmt(grand_vat),\n \"gross\": fmt(grand_gross),\n },\n }\n\n\nif __name__ == \"__main__\":\n import sys\n ledger = json.load(sys.stdin)\n print(json.dumps(build_report(ledger), indent=2))"}], "meta": {"idx": 2392, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 607, "latency_s": 9.6}} +{"prompt": [{"role": "user", "content": "You are given a list of journal entries, each a dict with keys 'date' (ISO string), 'account' (string), and 'amount' (string or int decimal, positive for debit, negative for credit). Write a function `summarize(entries)` that returns a dict with three items: 'net_income' (revenues minus expenses, where accounts starting with 'Revenue:' are revenues and 'Expense:' are expenses), 'total_assets' (sum of amounts in accounts starting with 'Asset:'), and 'owner_equity' (sum of 'Equity:' accounts plus net_income). All money values must be computed with Decimal and rounded to 2 places with ROUND_HALF_UP, returned as Decimal objects. Accounts not matching any of these prefixes (e.g. 'Liability:') must be ignored in the revenue/expense/asset sums but equity is still assets minus liabilities implicitly via net_income inclusion per the formula above. Example: entries = [{'date':'2024-01-05','account':'Asset:Cash','amount':'1000.005'}, {'date':'2024-01-05','account':'Revenue:Sales','amount':'-200.00'}, {'date':'2024-01-05','account':'Expense:Rent','amount':'150.00'}] gives net_income = Decimal('50.00') (revenue 200 minus expense 150), total_assets = Decimal('1000.01') (1000.005 rounds to 1000.01), owner_equity = Decimal('1050.01')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize(entries):\n revenue = Decimal('0')\n expense = Decimal('0')\n assets = Decimal('0')\n equity_accounts = Decimal('0')\n\n for entry in entries:\n account = entry['account']\n amount = Decimal(str(entry['amount']))\n if account.startswith('Revenue:'):\n revenue += -amount\n elif account.startswith('Expense:'):\n expense += amount\n elif account.startswith('Asset:'):\n assets += amount\n elif account.startswith('Equity:'):\n equity_accounts += amount\n\n net_income = revenue - expense\n owner_equity = equity_accounts + net_income\n\n def q(x):\n return x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n return {\n 'net_income': q(net_income),\n 'total_assets': q(assets),\n 'owner_equity': q(owner_equity),\n }\n\n\nif __name__ == '__main__':\n entries = [\n {'date': '2024-01-05', 'account': 'Asset:Cash', 'amount': '1000.005'},\n {'date': '2024-01-05', 'account': 'Revenue:Sales', 'amount': '-200.00'},\n {'date': '2024-01-05', 'account': 'Expense:Rent', 'amount': '150.00'},\n ]\n result = summarize(entries)\n print(result)\n assert result['net_income'] == Decimal('50.00')\n assert result['total_assets'] == Decimal('1000.01')\n assert result['owner_equity'] == Decimal('1050.01')"}], "meta": {"idx": 2397, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 679, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "You are given a list of bookkeeping entries, each a tuple (account, debit, credit) where account is a string like 'Cash', 'Revenue', and debit/credit are Decimal amounts (at least one is zero). Build a trial balance and derive two report figures: (1) total revenue, the sum of credits minus debits for accounts whose name starts with 'Revenue', and (2) net cash, the sum of debits minus credits for accounts whose name starts with 'Cash'. All amounts must be handled with Decimal and each report figure must be rounded to 2 places with ROUND_HALF_UP. Input example: [('Cash', '100.00', '0'), ('Revenue', '0', '100.00'), ('Cash', '0.005', '0'), ('Expenses:Rent', '50.00', '0')]. Expected output: a dict {'total_revenue': Decimal('100.00'), 'net_cash': Decimal('100.01')} \u2014 note the 0.005 debit rounds cash up to 100.01. Write a function summarize_ledger(entries) that returns this dict; accounts with neither prefix are ignored for the two figures."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize_ledger(entries):\n total_revenue = Decimal('0')\n net_cash = Decimal('0')\n for account, debit, credit in entries:\n d = Decimal(debit)\n c = Decimal(credit)\n if account.startswith('Revenue'):\n total_revenue += c - d\n elif account.startswith('Cash'):\n net_cash += d - c\n\n def round2(x):\n return x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n return {\n 'total_revenue': round2(total_revenue),\n 'net_cash': round2(net_cash),\n }\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', '100.00', '0'),\n ('Revenue', '0', '100.00'),\n ('Cash', '0.005', '0'),\n ('Expenses:Rent', '50.00', '0'),\n ]\n print(summarize_ledger(entries))"}], "meta": {"idx": 2375, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "deepinfra", "in_tokens": 204, "out_tokens": 516, "latency_s": 6.0}} +{"prompt": [{"role": "user", "content": "Write a function `t_account_balance(entries)` that computes the balance of a T-account from a list of journal entries. Each entry is a tuple `(side, amount)` where `side` is either `'debit'` or `'credit'` and `amount` is a string representing a monetary value (e.g., `'100.50'`). Use `decimal.Decimal` for exact arithmetic, quantize the final result to 2 decimal places with `ROUND_HALF_UP`, and return the balance as a string: debits minus credits, formatted with exactly two decimal places (e.g., `'250.00'`). If the entries list is empty, return `'0.00'`. Example: entries = [('debit', '100.00'), ('credit', '30.25'), ('debit', '5.25')] should return `'75.00'` because 100.00 - 30.25 + 5.25 = 75.00. Invalid side values should raise a `ValueError`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef t_account_balance(entries):\n \"\"\"Compute the balance (debits - credits) of a T-account.\n\n Args:\n entries: list of (side, amount) tuples, side is 'debit' or 'credit',\n amount is a string monetary value.\n\n Returns:\n The balance as a string with exactly two decimal places.\n\n Raises:\n ValueError: if a side is not 'debit' or 'credit'.\n \"\"\"\n balance = Decimal('0.00')\n for side, amount in entries:\n if side == 'debit':\n balance += Decimal(amount)\n elif side == 'credit':\n balance -= Decimal(amount)\n else:\n raise ValueError(\"side must be 'debit' or 'credit', got %r\" % (side,))\n balance = balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return str(balance)"}], "meta": {"idx": 2395, "topic": "general ledger and T-account operations", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 411, "latency_s": 16.7}} +{"prompt": [{"role": "user", "content": "You are given a general ledger as a list of journal entries, where each entry is a tuple (account, debit, credit) with amounts expressed as Decimal. Build a trial balance report: for each account (sorted alphabetically) compute the net balance, where balance = total debits - total credits. Accounts with a positive balance are 'DR', negative are 'CR', and exactly zero are listed with side '-'. The trial balance is 'BALANCED' if the sum of all net balances equals Decimal('0.00'), otherwise 'OUT OF BALANCE' with the difference shown to 2 decimal places. Additionally, detect imbalance per entry: an entry is internally consistent only if debit == credit; report the count of unbalanced entries. Round all displayed amounts to 2 decimal places using ROUND_HALF_UP. Example: entries = [('Cash', Decimal('100.00'), Decimal('100.00')), ('Rent Expense', Decimal('50.005'), Decimal('0')), ('Accounts Payable', Decimal('0'), Decimal('50.005'))] yields: Cash - 0.00 -, Rent Expense 50.01 DR, Accounts Payable 50.01 CR, total 0.00 -> BALANCED, unbalanced_entries = 1 (the two expense entries each have debit != credit). Write a function trial_balance(entries) returning a dict with keys 'lines' (list of (account, amount_str, side)), 'status', 'difference', and 'unbalanced_entries'."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _fmt(d):\n return str(d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))\n\n\ndef trial_balance(entries):\n balances = {}\n unbalanced = 0\n for account, debit, credit in entries:\n debit = Decimal(debit)\n credit = Decimal(credit)\n if debit != credit:\n unbalanced += 1\n balances[account] = balances.get(account, Decimal('0')) + debit - credit\n\n lines = []\n total = Decimal('0')\n for account in sorted(balances):\n bal = balances[account].quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n total += bal\n side = 'DR' if bal > 0 else ('CR' if bal < 0 else '-')\n lines.append((account, _fmt(abs(bal)), side))\n\n total = total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if total == Decimal('0.00'):\n status = 'BALANCED'\n else:\n status = 'OUT OF BALANCE'\n\n return {\n 'lines': lines,\n 'status': status,\n 'difference': _fmt(abs(total)),\n 'unbalanced_entries': unbalanced,\n }\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n entries = [\n ('Cash', Decimal('100.00'), Decimal('100.00')),\n ('Rent Expense', Decimal('50.005'), Decimal('0')),\n ('Accounts Payable', Decimal('0'), Decimal('50.005')),\n ]\n print(trial_balance(entries))"}], "meta": {"idx": 2400, "topic": "trial balance construction and imbalance detection", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 679, "latency_s": 9.0}} +{"prompt": [{"role": "user", "content": "Create a dataclass `LedgerEntry` representing a bookkeeping entry with fields: `date` (str, ISO format), `description` (str), `debit` (Decimal, default 0), and `credit` (Decimal, default 0). Then write a function `balance(entries)` that takes a list of `LedgerEntry` objects and returns a tuple `(total_debits, total_credits, balance)` where the first two are Decimals rounded to 2 places with ROUND_HALF_UP, and `balance` is the rounded debit total minus the rounded credit total. Entries where both debit and credit are 0 should be ignored in the totals. For example, given entries [('2024-01-01','Opening balance', Decimal('100.00'), Decimal('0')), ('2024-01-02','Coffee', Decimal('0'), Decimal('3.455'))], the function returns (Decimal('100.00'), Decimal('3.46'), Decimal('96.54'))."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import List, Tuple\n\n\n@dataclass\nclass LedgerEntry:\n date: str\n description: str\n debit: Decimal = Decimal('0')\n credit: Decimal = Decimal('0')\n\n def __post_init__(self):\n self.debit = Decimal(self.debit)\n self.credit = Decimal(self.credit)\n\n\ndef _round2(value: Decimal) -> Decimal:\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef balance(entries: List[LedgerEntry]) -> Tuple[Decimal, Decimal, Decimal]:\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n for e in entries:\n if e.debit == 0 and e.credit == 0:\n continue\n total_debits += e.debit\n total_credits += e.credit\n total_debits = _round2(total_debits)\n total_credits = _round2(total_credits)\n return total_debits, total_credits, _round2(total_debits - total_credits)\n\n\nif __name__ == '__main__':\n entries = [\n LedgerEntry('2024-01-01', 'Opening balance', Decimal('100.00'), Decimal('0')),\n LedgerEntry('2024-01-02', 'Coffee', Decimal('0'), Decimal('3.455')),\n LedgerEntry('2024-01-03', 'Empty note'),\n ]\n result = balance(entries)\n print(result)\n assert result == (Decimal('100.00'), Decimal('3.46'), Decimal('96.54'))"}], "meta": {"idx": 2391, "topic": "accounting record dataclasses and schemas", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 544, "latency_s": 33.5}} +{"prompt": [{"role": "user", "content": "Write a function `reconcile_petty_cash(log, replenish_threshold=Decimal('50.00'))` that processes a petty cash log and returns a replenishment report. The log is a list of tuples `(date, description, amount)`, where `amount` is a Decimal that is negative for disbursements (money paid out) and positive for contributions (money added). The function must: (1) compute a running balance starting from zero; (2) flag any entry where the running balance drops below zero as 'OVERDRAWN'; (3) determine the final balance, correctly rounded to 2 decimal places with ROUND_HALF_UP; (4) decide whether replenishment is needed \u2014 if the final balance is strictly below the replenishment threshold, the report should include a `replenish_amount` equal to the total disbursements (sum of negative amounts, as a positive value) needed to restore the fund to its highest historical balance, otherwise `replenish_amount` is Decimal('0.00'). Return a dictionary with keys 'entries' (list of dicts with keys 'date', 'description', 'amount', 'balance', 'flag'), 'final_balance', 'replenish_amount', and 'needs_replenishment' (boolean). Example: log = [('2024-01-02', 'Opening float', Decimal('100.00')), ('2024-01-05', 'Taxi fare', Decimal('-18.50')), ('2024-01-07', 'Office snacks', Decimal('-22.25')), ('2024-01-09', 'Bus tickets', Decimal('-15.00'))] gives final_balance Decimal('44.25'), needs_replenishment True, and replenish_amount Decimal('55.75') (restoring the fund to its peak balance of 100.00). Use only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef reconcile_petty_cash(log, replenish_threshold=Decimal('50.00')):\n entries = []\n balance = Decimal('0.00')\n peak = Decimal('0.00')\n total_disbursed = Decimal('0.00')\n\n for date, description, amount in log:\n if not isinstance(amount, Decimal):\n amount = Decimal(str(amount))\n balance += amount\n if amount < 0:\n total_disbursed += -amount\n flag = 'OVERDRAWN' if balance < 0 else ''\n entries.append({\n 'date': date,\n 'description': description,\n 'amount': amount,\n 'balance': balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP),\n 'flag': flag,\n })\n if balance > peak:\n peak = balance\n\n final_balance = balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n if final_balance < replenish_threshold:\n replenish_amount = (peak - balance).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP\n )\n needs_replenishment = True\n else:\n replenish_amount = Decimal('0.00')\n needs_replenishment = False\n\n if replenish_amount < 0:\n replenish_amount = Decimal('0.00')\n\n return {\n 'entries': entries,\n 'final_balance': final_balance,\n 'replenish_amount': replenish_amount,\n 'needs_replenishment': needs_replenishment,\n }\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n log = [\n ('2024-01-02', 'Opening float', Decimal('100.00')),\n ('2024-01-05', 'Taxi fare', Decimal('-18.50')),\n ('2024-01-07', 'Office snacks', Decimal('-22.25')),\n ('2024-01-09', 'Bus tickets', Decimal('-15.00')),\n ]\n report = reconcile_petty_cash(log)\n print(report['final_balance']) # 44.25\n print(report['needs_replenishment']) # True\n print(report['replenish_amount']) # 55.75\n for e in report['entries']:\n print(e)"}], "meta": {"idx": 2402, "topic": "petty cash logs and replenishment", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 896, "latency_s": 8.1}} +{"prompt": [{"role": "user", "content": "A company keeps its books on a cash basis but needs an accrual-basis net income figure for a period. Given a list of cash transactions and a list of period-end adjustments, compute accrual net income using Decimal arithmetic with ROUND_HALF_UP rounding to cents. Each cash transaction is a tuple (date, description, amount) where positive amounts are revenues received in cash and negative amounts are cash expenses paid. Each adjustment is a tuple (description, amount) representing accrual corrections: positive amounts are revenues earned but not yet received, negative amounts are expenses incurred but not yet paid. The function accrual_net_income(cash_txns, adjustments) should return (cash_net_income, accrual_net_income) as Decimals rounded to 2 decimal places. For example, cash_txns = [('2024-01-05','Consulting fee received', Decimal('1500.00')), ('2024-01-20','Paid rent', Decimal('-800.00'))] and adjustments = [('Earned but unbilled fees', Decimal('600.00')), ('Accrued utilities expense', Decimal('-150.00'))] gives cash net income of 700.00 and accrual net income of 1150.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef accrual_net_income(cash_txns, adjustments):\n cash_total = sum((t[2] for t in cash_txns), Decimal('0'))\n adj_total = sum((a[1] for a in adjustments), Decimal('0'))\n cash_ni = cash_total.quantize(TWO, rounding=ROUND_HALF_UP)\n accrual_ni = (cash_total + adj_total).quantize(TWO, rounding=ROUND_HALF_UP)\n return cash_ni, accrual_ni\n\n\nif __name__ == '__main__':\n cash_txns = [\n ('2024-01-05', 'Consulting fee received', Decimal('1500.00')),\n ('2024-01-20', 'Paid rent', Decimal('-800.00')),\n ]\n adjustments = [\n ('Earned but unbilled fees', Decimal('600.00')),\n ('Accrued utilities expense', Decimal('-150.00')),\n ]\n print(accrual_net_income(cash_txns, adjustments))"}], "meta": {"idx": 2403, "topic": "accrual versus cash basis adjustments", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 485, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "Write a function `inventory_value(layers, units_sold)` that computes the value of remaining inventory under three costing methods: FIFO, LIFO, and weighted average. Each purchase is given as a list of `[units, unit_cost]` tuples in chronological order (unit_cost is a string like '10.50' to be parsed as Decimal). `units_sold` is the total number of units sold; assume sales occur after all purchases and inventory never goes negative. Under FIFO, the oldest layers are sold first; under LIFO, the newest layers are sold first; under weighted average, the average cost per unit (total cost / total units, rounded HALF_UP to 2 decimal places) applies to all sales. Return a dict with keys 'FIFO', 'LIFO', 'AVG' mapping to the remaining inventory value as a Decimal rounded to 2 decimal places. Example: layers = [(10, '10.00'), (10, '12.00')], units_sold = 15 -> FIFO: sell 10 @10.00 and 5 @12.00, leaving 5 @12.00 = 60.00; LIFO: sell 10 @12.00 and 5 @10.00, leaving 5 @10.00 = 50.00; AVG: average cost = 220.00/20 = 11.00, remaining 5 units = 55.00. So the result is {'FIFO': Decimal('60.00'), 'LIFO': Decimal('50.00'), 'AVG': Decimal('55.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _round2(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef inventory_value(layers, units_sold):\n layers = [(int(u), Decimal(c)) for u, c in layers]\n remaining = units_sold\n\n # FIFO: consume from the front\n fifo = Decimal('0')\n idx = 0\n left = remaining\n while left > 0:\n u, c = layers[idx]\n take = min(u, left)\n left -= take\n idx += 1\n for u, c in layers[idx:]:\n fifo += u * c\n\n # LIFO: consume from the back\n lifo = Decimal('0')\n idx = len(layers) - 1\n left = remaining\n while left > 0:\n u, c = layers[idx]\n take = min(u, left)\n left -= take\n idx -= 1\n for u, c in layers[:idx + 1]:\n lifo += u * c\n\n # Weighted average\n total_units = sum(u for u, _ in layers)\n total_cost = sum(u * c for u, c in layers)\n avg_cost = _round2(total_cost / total_units)\n avg = _round2(avg_cost * (total_units - remaining))\n avg = _round2(avg_cost * (total_units - units_sold))\n\n return {'FIFO': _round2(fifo), 'LIFO': _round2(lifo), 'AVG': avg}\n\n\nif __name__ == '__main__':\n result = inventory_value([(10, '10.00'), (10, '12.00')], 15)\n assert result == {'FIFO': Decimal('60.00'), 'LIFO': Decimal('50.00'), 'AVG': Decimal('55.00')}, result\n print(result)"}], "meta": {"idx": 2398, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 647, "latency_s": 26.3}} +{"prompt": [{"role": "user", "content": "Design an immutable audit-trail ledger for a small business. Each entry is a namedtuple-like immutable record with: a monotonically increasing integer `entry_id`, an ISO date string, a description, a debit account, a credit account, and a `Decimal` amount (rounded to 2 places with ROUND_HALF_UP). Implement a class `AuditLedger` with methods: `post(date, description, debit_account, credit_account, amount)` that appends a new entry (never mutates existing ones) and returns the entry; `balance(account)` returning the net Decimal balance of an account (credits add, debits subtract); `entries_for(account)` returning a tuple of entries touching that account in posting order; and `verify()` that checks (1) every entry's amount is positive and rounded to exactly 2 decimal places, and (2) over all entries, the sum of debits equals the sum of credits (double-entry integrity), returning True/False. Attempting to mutate an entry attribute (e.g. `entry.amount = 0`) must raise an error. Example: posting `('2024-01-05', 'Sale', 'Cash', 'Revenue', Decimal('10.005'))` stores amount `10.01` (ROUND_HALF_UP) with entry_id 0; `balance('Cash')` is `10.01`, `balance('Revenue')` is `-10.01`, and `verify()` is True. Write a program demonstrating these requirements with assertions."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import namedtuple\nfrom datetime import date\n\nEntry = namedtuple('Entry', ['entry_id', 'date', 'description', 'debit_account', 'credit_account', 'amount'])\n\nclass AuditLedger:\n TWO_PLACES = Decimal('0.01')\n\n def __init__(self):\n self._entries = []\n self._next_id = 0\n\n def post(self, date, description, debit_account, credit_account, amount):\n amount = Decimal(amount).quantize(self.TWO_PLACES, rounding=ROUND_HALF_UP)\n entry = Entry(self._next_id, date, description, debit_account, credit_account, amount)\n self._next_id += 1\n self._entries.append(entry)\n return entry\n\n def balance(self, account):\n total = Decimal('0.00')\n for e in self._entries:\n if e.debit_account == account:\n total -= e.amount\n if e.credit_account == account:\n total += e.amount\n return total.quantize(self.TWO_PLACES)\n\n def entries_for(self, account):\n return tuple(e for e in self._entries if account in (e.debit_account, e.credit_account))\n\n def verify(self):\n debit_sum = Decimal('0.00')\n credit_sum = Decimal('0.00')\n for e in self._entries:\n if e.amount <= 0:\n return False\n if e.amount != e.amount.quantize(self.TWO_PLACES):\n return False\n debit_sum += e.amount\n credit_sum += e.amount\n return debit_sum == credit_sum\n\nif __name__ == '__main__':\n ledger = AuditLedger()\n e0 = ledger.post('2024-01-05', 'Sale', 'Cash', 'Revenue', Decimal('10.005'))\n assert e0.entry_id == 0\n assert e0.amount == Decimal('10.01')\n e1 = ledger.post('2024-01-06', 'Rent paid', 'RentExpense', 'Cash', Decimal('250.00'))\n assert e1.entry_id == 1\n assert ledger.balance('Cash') == Decimal('-239.99')\n assert ledger.balance('Revenue') == Decimal('10.01')\n assert ledger.balance('RentExpense') == Decimal('-250.00')\n assert ledger.entries_for('Cash') == (e0, e1)\n assert ledger.verify() is True\n try:\n e0.amount = Decimal('0.00')\n raise AssertionError('mutation should have failed')\n except AttributeError:\n pass\n bad = AuditLedger()\n bad.post('2024-02-01', 'Bad', 'A', 'B', Decimal('-5.00'))\n assert bad.verify() is False\n print('All audit ledger checks passed.')"}], "meta": {"idx": 2399, "topic": "audit trails and immutable entry logs", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 943, "latency_s": 28.6}} +{"prompt": [{"role": "user", "content": "Write a function `aging_report(invoices, as_of)` that produces an accounts receivable/payable aging report. Each invoice is a dict with keys 'id' (str), 'due_date' (str, ISO format YYYY-MM-DD), and 'amount' (str or Decimal, the outstanding balance). `as_of` is the report date in the same format. Buckets are: 'current' (due date >= as_of), '1-30' (1-30 days overdue), '31-60', '61-90', and '90+' (more than 90 days overdue). Return a dict mapping each bucket name to the total outstanding amount as a Decimal rounded to 2 places (ROUND_HALF_UP), with all five buckets always present. Amounts must be handled as exact Decimals, never floats. Example: invoices = [{'id': 'A', 'due_date': '2024-05-01', 'amount': '150.00'}, {'id': 'B', 'due_date': '2024-03-15', 'amount': '99.995'}, {'id': 'C', 'due_date': '2024-06-30', 'amount': '200'}] with as_of='2024-05-31' yields {'current': Decimal('200.00'), '1-30': Decimal('150.00'), '31-60': Decimal('0.00'), '61-90': Decimal('0.00'), '90+': Decimal('0.00')} plus invoice B (77 days overdue) in '61-90' with Decimal('100.00') after rounding 99.995 half-up, i.e. {'current': Decimal('200.00'), '1-30': Decimal('150.00'), '31-60': Decimal('0.00'), '61-90': Decimal('100.00'), '90+': Decimal('0.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nBUCKETS = ['current', '1-30', '31-60', '61-90', '90+']\n\ndef aging_report(invoices, as_of):\n as_of_date = date.fromisoformat(as_of)\n totals = {b: Decimal('0.00') for b in BUCKETS}\n for inv in invoices:\n amount = Decimal(str(inv['amount']))\n due = date.fromisoformat(inv['due_date'])\n if due >= as_of_date:\n bucket = 'current'\n else:\n days_overdue = (as_of_date - due).days\n if days_overdue <= 30:\n bucket = '1-30'\n elif days_overdue <= 60:\n bucket = '31-60'\n elif days_overdue <= 90:\n bucket = '61-90'\n else:\n bucket = '90+'\n totals[bucket] += amount\n for b in BUCKETS:\n totals[b] = totals[b].quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return totals\n\nif __name__ == '__main__':\n invoices = [\n {'id': 'A', 'due_date': '2024-05-01', 'amount': '150.00'},\n {'id': 'B', 'due_date': '2024-03-15', 'amount': '99.995'},\n {'id': 'C', 'due_date': '2024-06-30', 'amount': '200'},\n ]\n result = aging_report(invoices, '2024-05-31')\n print(result)"}], "meta": {"idx": 2401, "topic": "accounts receivable and payable aging reports", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 634, "latency_s": 27.1}} +{"prompt": [{"role": "user", "content": "Write a function `post_entries(entries)` that takes a list of double-entry journal entries and returns the resulting ledger balances as a dict mapping account names to Decimal amounts. Each journal entry is a dict with keys 'description' (str) and 'lines' (list of (account, amount) tuples), where a positive amount is a debit and a negative amount is a credit. Before posting, validate each entry with the double-entry rule: the sum of all line amounts must equal exactly 0 (use Decimal arithmetic; raise ValueError with a message containing 'unbalanced' and the description if it does not). After validation, post all lines by adding each amount to the corresponding account's running balance. Accounts not seen before start at Decimal('0.00'). Round each final balance to 2 decimal places using ROUND_HALF_UP. Example: entries = [{'description': 'Open business', 'lines': [('Cash', Decimal('100.00')), ('Owner Equity', Decimal('-100.00'))]}, {'description': 'Buy supplies', 'lines': [('Supplies', Decimal('40.00')), ('Cash', Decimal('-40.00'))]}] should return {'Cash': Decimal('60.00'), 'Owner Equity': Decimal('-100.00'), 'Supplies': Decimal('40.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef post_entries(entries):\n \"\"\"Validate and post double-entry journal entries, returning account balances.\"\"\"\n balances = {}\n for entry in entries:\n description = entry['description']\n lines = entry['lines']\n total = sum((amount for _, amount in lines), Decimal('0'))\n if total != 0:\n raise ValueError(\n f\"unbalanced entry '{description}': debits and credits differ by {total}\"\n )\n for account, amount in lines:\n balances[account] = balances.get(account, Decimal('0')) + amount\n return {\n account: balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n for account, balance in balances.items()\n }\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n entries = [\n {\n 'description': 'Open business',\n 'lines': [('Cash', Decimal('100.00')), ('Owner Equity', Decimal('-100.00'))],\n },\n {\n 'description': 'Buy supplies',\n 'lines': [('Supplies', Decimal('40.00')), ('Cash', Decimal('-40.00'))],\n },\n ]\n result = post_entries(entries)\n print(result)\n assert result == {\n 'Cash': Decimal('60.00'),\n 'Owner Equity': Decimal('-100.00'),\n 'Supplies': Decimal('40.00'),\n }\n try:\n post_entries([\n {\n 'description': 'Bad entry',\n 'lines': [('Cash', Decimal('10.00')), ('Revenue', Decimal('-9.00'))],\n }\n ])\n raise AssertionError('expected ValueError')\n except ValueError as e:\n assert 'unbalanced' in str(e) and 'Bad entry' in str(e)\n print('All checks passed.')"}], "meta": {"idx": 2404, "topic": "double-entry journal entries and posting rules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 743, "latency_s": 14.0}} +{"prompt": [{"role": "user", "content": "A small office-supplies store buys boxes of printer paper in several batches and wants to value its remaining inventory under three common methods: FIFO, LIFO, and weighted average cost. Each purchase is recorded as (quantity, unit_cost) in the order the purchases occurred, and a quantity of units is sold during the period. Write a function `value_inventory(purchases, units_sold)` that takes a list of (quantity, unit_cost) tuples (unit_cost given as a string like '12.50' to avoid float issues) and an integer units_sold, and returns a dictionary with keys 'FIFO', 'LIFO', and 'weighted_average' mapping to the remaining inventory value as a Decimal rounded to 2 places with ROUND_HALF_UP. Assume units_sold never exceeds total purchased. For example, purchases = [(100, '10.00'), (50, '12.00'), (50, '15.00')] with units_sold = 80: FIFO removes 80 units from the first batch, leaving 20 at 10.00 plus 50 at 12.00 plus 50 at 15.00 = 1550.00; LIFO removes 50 from the third batch and 30 from the second, leaving 100*10.00 + 20*12.00 = 1240.00; weighted average cost is (100*10.00 + 50*12.00 + 50*15.00)/200 = 11.75, and 120 remaining units are worth 1410.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef value_inventory(purchases, units_sold):\n batches = [(int(q), Decimal(str(c))) for q, c in purchases]\n total_units = sum(q for q, _ in batches)\n remaining = total_units - units_sold\n\n # FIFO\n fifo = Decimal('0')\n left_to_remove = units_sold\n\n def _fifo_value():\n value = Decimal('0')\n rem = units_sold\n for q, c in batches:\n keep = max(0, q - rem)\n rem = max(0, rem - q)\n value += keep * c\n return value\n\n def _lifo_value():\n value = Decimal('0')\n rem = units_sold\n for q, c in reversed(batches):\n keep = max(0, q - rem)\n rem = max(0, rem - q)\n value += keep * c\n return value\n\n def _wa_value():\n total_cost = sum(q * c for q, c in batches)\n avg = total_cost / Decimal(total_units)\n return (avg * remaining).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n def _round(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n return {\n 'FIFO': _round(_fifo_value()),\n 'LIFO': _round(_lifo_value()),\n 'weighted_average': _wa_value(),\n }\n\nif __name__ == '__main__':\n result = value_inventory([(100, '10.00'), (50, '12.00'), (50, '15.00')], 80)\n print(result)\n assert result == {\n 'FIFO': Decimal('1550.00'),\n 'LIFO': Decimal('1240.00'),\n 'weighted_average': Decimal('1410.00'),\n }"}], "meta": {"idx": 2408, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 683, "latency_s": 7.0}} +{"prompt": [{"role": "user", "content": "Implement a double-entry journal and ledger posting engine. Each journal entry consists of a date, a memo, and a list of lines, where each line has an account name, a 'debit' or 'credit' side, and a Decimal money amount rounded to 2 places. An entry is valid only if it balances: total debits equal total credits (after rounding each line to 2 places); invalid entries must be rejected with a ValueError. Write a function `post_entries(entries)` that returns a dict mapping each account name to its balance, where debit-normal accounts (assets/expenses, i.e. names starting with 'Asset' or 'Expense') have balance = total debits - total credits, and all other accounts have balance = total credits - total debits. Balances must be exact Decimals quantized to 0.01. Example: entry with lines [('Asset:Cash', 'debit', Decimal('100.00')), ('Equity:Capital', 'credit', Decimal('100.00'))] followed by entry [('Expense:Rent', 'debit', Decimal('40.00')), ('Asset:Cash', 'credit', Decimal('40.00'))] must produce {'Asset:Cash': Decimal('60.00'), 'Equity:Capital': Decimal('100.00'), 'Expense:Rent': Decimal('40.00')}. Entries may be given as dicts like {'date': '2024-01-01', 'memo': 'open', 'lines': [(account, side, amount), ...]}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _round(amount):\n return Decimal(amount).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef _is_debit_normal(account):\n return account.startswith('Asset') or account.startswith('Expense')\n\n\ndef post_entries(entries):\n \"\"\"Post balanced double-entry journal entries and return account balances.\n\n Each entry is a dict with keys 'date', 'memo', and 'lines', where lines\n is a sequence of (account, side, amount) tuples. Raises ValueError if\n an entry's debits do not equal its credits.\n \"\"\"\n balances = {}\n for entry in entries:\n debits = Decimal('0.00')\n credits = Decimal('0.00')\n posted = []\n for account, side, amount in entry['lines']:\n amt = _round(amount)\n if side == 'debit':\n debits += amt\n elif side == 'credit':\n credits += amt\n else:\n raise ValueError(\n \"invalid side {!r} in entry {!r}\".format(side, entry.get('memo'))\n )\n posted.append((account, side, amt))\n if debits != credits:\n raise ValueError(\n 'unbalanced entry {!r}: debits {} != credits {}'.format(\n entry.get('memo'), debits, credits\n )\n )\n for account, side, amt in posted:\n if account not in balances:\n balances[account] = Decimal('0.00')\n if _is_debit_normal(account):\n if side == 'debit':\n balances[account] += amt\n else:\n balances[account] -= amt\n else:\n if side == 'credit':\n balances[account] += amt\n else:\n balances[account] -= amt\n return {acct: bal.quantize(TWO, rounding=ROUND_HALF_UP) for acct, bal in balances.items()}\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n entries = [\n {\n 'date': '2024-01-01',\n 'memo': 'open',\n 'lines': [\n ('Asset:Cash', 'debit', Decimal('100.00')),\n ('Equity:Capital', 'credit', Decimal('100.00')),\n ],\n },\n {\n 'date': '2024-01-02',\n 'memo': 'rent',\n 'lines': [\n ('Expense:Rent', 'debit', Decimal('40.00')),\n ('Asset:Cash', 'credit', Decimal('40.00')),\n ],\n },\n ]\n result = post_entries(entries)\n expected = {\n 'Asset:Cash': Decimal('60.00'),\n 'Equity:Capital': Decimal('100.00'),\n 'Expense:Rent': Decimal('40.00'),\n }\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2407, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1024, "latency_s": 10.1}} +{"prompt": [{"role": "user", "content": "A small business posts a recurring monthly rent expense. Write a function `generate_rent_entries(monthly_amount, start_date, months)` that produces journal entries for the rent for a given number of months starting from `start_date` (a `datetime.date`). Each entry debits the expense account 'Rent Expense' and credits 'Accounts Payable' with the monthly amount. Use `Decimal` for money and quantize each amount to 2 decimal places. Each posting date is the same day-of-month as `start_date` in each subsequent month; if that day does not exist in a month (e.g. day 31 in a 30-day month), use the last valid day of that month. Return a list of tuples `(posting_date, debit_account, credit_account, amount)`. Example: with monthly_amount=Decimal('1200.00'), start_date=date(2024,1,31), months=3, the posting dates are 2024-01-31, 2024-02-29 (2024 is a leap year), and 2024-03-31, each with amount Decimal('1200.00')."}], "completion": [{"role": "assistant", "content": "from datetime import date\nfrom decimal import Decimal\nimport calendar\n\ndef generate_rent_entries(monthly_amount, start_date, months):\n amount = Decimal(monthly_amount).quantize(Decimal('0.01'))\n entries = []\n for i in range(months):\n year = start_date.year + (start_date.month - 1 + i) // 12\n month = (start_date.month - 1 + i) % 12 + 1\n day = min(start_date.day, calendar.monthrange(year, month)[1])\n posting_date = date(year, month, day)\n entries.append((posting_date, 'Rent Expense', 'Accounts Payable', amount))\n return entries\n\nif __name__ == '__main__':\n result = generate_rent_entries(Decimal('1200.00'), date(2024, 1, 31), 3)\n for entry in result:\n print(entry)"}], "meta": {"idx": 2411, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 423, "latency_s": 3.7}} +{"prompt": [{"role": "user", "content": "You are the bookkeeper for a company whose reporting (base) currency is USD. Given a chronological journal of foreign-currency cash movements and period-end closing rates, compute the realized and unrealized FX gain/loss per currency using the weighted-average cost method. Each transaction is a dict with keys 'currency' (e.g. 'EUR'), 'units' (a Decimal string; positive = acquiring foreign currency, negative = disposing of it), and 'rate' (Decimal string: USD per 1 unit of that currency at transaction time). For each acquisition, add units and add units*rate to that currency's accumulated base-currency cost, keeping the average cost rate = accumulated cost / accumulated units at full Decimal precision. For each disposal, proceeds = abs(units)*rate, cost of goods sold = abs(units)*average_rate, and the realized gain/loss for that transaction is quantize(proceeds - cost_of_goods_sold, 0.01, ROUND_HALF_UP); then reduce accumulated cost by the unquantized cost of goods sold and recompute the average rate. A disposal that exceeds the held units must raise ValueError. At period end, unrealized gain/loss per currency = quantize(remaining_units * closing_rate - remaining_cost, 0.01, ROUND_HALF_UP). Write a function compute_fx_gain_loss(transactions, closing_rates) that returns a dict mapping each currency to {'realized_gain': Decimal, 'unrealized_gain': Decimal, 'closing_units': Decimal, 'closing_cost': Decimal} plus a 'TOTAL' key summing the gains (quantized to 0.01). Worked example: transactions EUR +1000 @1.10, EUR +500 @1.16, EUR -400 @1.20 with closing rate 1.15 give: after the buys the average rate is 1680/1500 = 1.12; the sale realizes quantize(480.00 - 448.00) = +32.00; unrealized = quantize(1100*1.15 - 1232.00) = +33.00; so EUR shows realized_gain 32.00, unrealized_gain 33.00, closing_units 1100, closing_cost 1232.00, and TOTAL realized 32.00, unrealized 33.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\ndef q2(x):\n \"\"\"Quantize a Decimal to 2 places, half-up.\"\"\"\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef compute_fx_gain_loss(transactions, closing_rates):\n \"\"\"\n Compute realized and unrealized FX gain/loss per currency using the\n weighted-average cost method.\n\n transactions: chronological list of dicts with keys\n 'currency' : str\n 'units' : Decimal or str (positive = acquire, negative = dispose)\n 'rate' : Decimal or str, base-currency units per 1 foreign unit\n closing_rates: dict currency -> Decimal or str (period-end rate)\n\n Returns dict: currency -> {\n 'realized_gain' : Decimal (2dp),\n 'unrealized_gain': Decimal (2dp),\n 'closing_units' : Decimal,\n 'closing_cost' : Decimal,\n } plus a 'TOTAL' key with summed realized/unrealized gains (2dp).\n \"\"\"\n # Per-currency running state: units held and accumulated base cost.\n state = {}\n # Per-currency accumulated realized gain (kept at cent precision\n # by summing per-transaction quantized gains).\n realized = {}\n\n for txn in transactions:\n cur = txn[\"currency\"]\n units = Decimal(str(txn[\"units\"]))\n rate = Decimal(str(txn[\"rate\"]))\n\n if cur not in state:\n state[cur] = {\"units\": Decimal(\"0\"), \"cost\": Decimal(\"0\")}\n realized[cur] = Decimal(\"0\")\n\n st = state[cur]\n\n if units > 0:\n # Acquisition: add units and their base-currency cost.\n st[\"units\"] += units\n st[\"cost\"] += units * rate\n elif units < 0:\n disposed = -units\n if disposed > st[\"units\"]:\n raise ValueError(\n \"Disposal of {} {} exceeds held balance of {} {}\".format(\n disposed, cur, st[\"units\"], cur\n )\n )\n if st[\"units\"] == 0:\n raise ValueError(\"Cannot dispose from zero balance of \" + cur)\n\n # Weighted-average cost rate (full precision).\n avg_rate = st[\"cost\"] / st[\"units\"]\n\n proceeds = disposed * rate\n cogs = disposed * avg_rate\n\n # Realized gain/loss for this transaction, quantized to cents.\n realized[cur] += q2(proceeds - cogs)\n\n # Reduce position by the unquantized cost of goods sold.\n st[\"units\"] -= disposed\n st[\"cost\"] -= cogs\n # Guard against tiny negative residue from Decimal division.\n if st[\"units\"] == 0:\n st[\"cost\"] = Decimal(\"0\")\n elif st[\"cost\"] < 0:\n st[\"cost\"] = Decimal(\"0\")\n else:\n # Zero-unit transaction: no effect.\n continue\n\n result = {}\n total_realized = Decimal(\"0\")\n total_unrealized = Decimal(\"0\")\n\n for cur in sorted(state):\n st = state[cur]\n units = st[\"units\"]\n cost = st[\"cost\"]\n\n if cur in closing_rates:\n closing_rate = Decimal(str(closing_rates[cur]))\n else:\n # No closing rate provided: treat unrealized as zero.\n closing_rate = None\n\n if closing_rate is not None and units != 0:\n unrealized = q2(units * closing_rate - cost)\n else:\n unrealized = q2(Decimal(\"0\"))\n\n result[cur] = {\n \"realized_gain\": q2(realized[cur]),\n \"unrealized_gain\": unrealized,\n \"closing_units\": units,\n \"closing_cost\": cost,\n }\n total_realized += q2(realized[cur])\n total_unrealized += unrealized\n\n result[\"TOTAL\"] = {\n \"realized_gain\": q2(total_realized),\n \"unrealized_gain\": q2(total_unrealized),\n }\n\n return result\n\n\nif __name__ == \"__main__\":\n # Worked example from the task statement.\n transactions = [\n {\"currency\": \"EUR\", \"units\": \"1000\", \"rate\": \"1.10\"},\n {\"currency\": \"EUR\", \"units\": \"500\", \"rate\": \"1.16\"},\n {\"currency\": \"EUR\", \"units\": \"-400\", \"rate\": \"1.20\"},\n ]\n closing_rates = {\"EUR\": \"1.15\"}\n\n report = compute_fx_gain_loss(transactions, closing_rates)\n\n eur = report[\"EUR\"]\n assert eur[\"realized_gain\"] == Decimal(\"32.00\")\n assert eur[\"unrealized_gain\"] == Decimal(\"33.00\")\n assert eur[\"closing_units\"] == Decimal(\"1100\")\n assert eur[\"closing_cost\"] == Decimal(\"1232.00\")\n assert report[\"TOTAL\"][\"realized_gain\"] == Decimal(\"32.00\")\n assert report[\"TOTAL\"][\"unrealized_gain\"] == Decimal(\"33.00\")\n\n # Overdraft protection.\n try:\n compute_fx_gain_loss(\n [{\"currency\": \"JPY\", \"units\": \"-100\", \"rate\": \"0.009\"}],\n {\"JPY\": \"0.009\"},\n )\n assert False, \"expected ValueError\"\n except ValueError:\n pass\n\n print(report)"}], "meta": {"idx": 2405, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1767, "latency_s": 23.5}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, useful_life, rate=None)` that builds a depreciation schedule for a bookkeeping report. If `rate` is None, use the straight-line method: each year's depreciation expense is (cost - salvage) / useful_life, computed with Decimal and rounded to the nearest cent with ROUND_HALF_UP. If `rate` is given (e.g. Decimal('0.40') for 40%), use the declining-balance method: each year's depreciation is the beginning book value multiplied by `rate`, rounded to cents with ROUND_HALF_UP, and the schedule stops (with a final adjusting entry) in the year the book value would drop to or below salvage, so that the ending book value never goes below salvage. The function takes Decimal inputs for cost, salvage, and rate, and an int for useful_life, and returns a list of tuples (year, depreciation_expense, beginning_book_value, ending_book_value) with all money amounts as Decimal rounded to cents. Example: cost=Decimal('10000.00'), salvage=Decimal('1000.00'), useful_life=5, rate=None should return years 1-5 where each depreciation expense is Decimal('1800.00') and the final ending book value is exactly Decimal('1000.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef depreciation_schedule(cost, salvage, useful_life, rate=None):\n cost = Decimal(cost)\n salvage = Decimal(salvage)\n schedule = []\n\n if rate is None:\n annual = _round_cents((cost - salvage) / Decimal(useful_life))\n book = cost\n for year in range(1, useful_life + 1):\n beginning = book\n if year == useful_life:\n depreciation = _round_cents(beginning - salvage)\n else:\n depreciation = annual\n ending = _round_cents(beginning - depreciation)\n schedule.append((year, depreciation, beginning, ending))\n book = ending\n return schedule\n\n rate = Decimal(rate)\n book = cost\n year = 0\n while book > salvage:\n year += 1\n beginning = book\n raw = beginning * rate\n if _round_cents(beginning - raw) < salvage:\n depreciation = _round_cents(beginning - salvage)\n else:\n depreciation = _round_cents(raw)\n ending = _round_cents(beginning - depreciation)\n schedule.append((year, depreciation, beginning, ending))\n book = ending\n if ending <= salvage:\n break\n return schedule\n\n\nif __name__ == '__main__':\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5):\n print(row)\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5, Decimal('0.40')):\n print(row)"}], "meta": {"idx": 2413, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 715, "latency_s": 6.0}} +{"prompt": [{"role": "user", "content": "You are maintaining the loan book for a small lender. Write a function `amortization_schedule(principal, annual_rate, years, payment)` that generates a monthly amortization schedule using Decimal arithmetic with ROUND_HALF_UP rounding to cents at each step. The monthly interest rate is annual_rate/12 (exact Decimal division, not rounded). Each month: interest = round(rate * previous_balance), principal_part = round(payment - interest) if a full payment fits, and the new balance = previous_balance - principal_part. On the final month, if the remaining balance plus interest is less than or equal to the payment, the payment is reduced to exactly settle the loan (balance becomes 0). If the loan is not fully repaid after years*12 months, raise ValueError('loan not fully amortized'). Return a list of tuples (month, payment, interest, principal_part, balance). Example: principal=Decimal('12000.00'), annual_rate=Decimal('0.06'), years=1, payment=Decimal('1030.00') must produce 12 rows ending with balance Decimal('0.00'); the first row is (1, Decimal('1030.00'), Decimal('60.00'), Decimal('970.00'), Decimal('11030.00')) since 12000 * 0.005 = 60.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortization_schedule(principal, annual_rate, years, payment):\n principal = Decimal(principal)\n annual_rate = Decimal(annual_rate)\n payment = Decimal(payment)\n monthly_rate = annual_rate / Decimal(12)\n n_months = int(years) * 12\n\n rows = []\n balance = _round_cents(principal)\n for month in range(1, n_months + 1):\n interest = _round_cents(balance * monthly_rate)\n if balance + interest <= payment:\n final_payment = _round_cents(balance + interest)\n principal_part = balance\n rows.append((month, final_payment, interest, principal_part, Decimal('0.00')))\n return rows\n actual_payment = _round_cents(payment)\n principal_part = _round_cents(actual_payment - interest)\n balance = _round_cents(balance - principal_part)\n rows.append((month, actual_payment, interest, principal_part, balance))\n raise ValueError('loan not fully amortized')\n\nif __name__ == '__main__':\n rows = amortization_schedule('12000.00', '0.06', 1, '1030.00')\n for row in rows:\n print(row)\n assert rows[0] == (1, Decimal('1030.00'), Decimal('60.00'), Decimal('970.00'), Decimal('11030.00'))\n assert rows[-1][4] == Decimal('0.00')\n assert len(rows) == 12"}], "meta": {"idx": 2409, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 658, "latency_s": 24.1}} +{"prompt": [{"role": "user", "content": "You are maintaining a fixed-asset ledger for a small business. Write a function `depreciation_schedule(cost, salvage, useful_life, method, rate=None)` that computes the annual depreciation schedule for an asset. For the 'straight_line' method, annual depreciation is (cost - salvage) / useful_life, applied each year until the asset's book value reaches salvage value. For the 'declining_balance' method, each year's depreciation is the book value at the start of the year multiplied by the given `rate` (a fraction like 0.40), but depreciation is capped so the book value never drops below the salvage value; the schedule runs for `useful_life` years. Use `Decimal` with two-decimal rounding (ROUND_HALF_UP) for all money amounts, and return a list of dictionaries, each with keys 'year', 'depreciation', 'book_value' (book value at end of that year). Example: straight_line with cost=Decimal('1000.00'), salvage=Decimal('100.00'), useful_life=3 returns [{year:1, depreciation:Decimal('300.00'), book_value:Decimal('700.00')}, {year:2, depreciation:Decimal('300.00'), book_value:Decimal('400.00')}, {year:3, depreciation:Decimal('300.00'), book_value:Decimal('100.00')}]. For declining_balance with cost=Decimal('1000.00'), salvage=Decimal('100.00'), useful_life=2, rate=Decimal('0.40'), year 1 depreciation is Decimal('400.00') leaving book value Decimal('600.00'), and year 2 depreciation is capped at Decimal('500.00') so the book value ends at Decimal('100.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef depreciation_schedule(cost, salvage, useful_life, method, rate=None):\n cost = Decimal(str(cost))\n salvage = Decimal(str(salvage))\n schedule = []\n\n if method == 'straight_line':\n annual = _round((cost - salvage) / Decimal(useful_life))\n book_value = cost\n for year in range(1, useful_life + 1):\n depreciation = annual\n if book_value - depreciation < salvage:\n depreciation = _round(book_value - salvage)\n book_value = _round(book_value - depreciation)\n schedule.append({'year': year, 'depreciation': depreciation,\n 'book_value': book_value})\n\n elif method == 'declining_balance':\n if rate is None:\n raise ValueError(\"rate is required for declining_balance method\")\n rate = Decimal(str(rate))\n book_value = cost\n for year in range(1, useful_life + 1):\n depreciation = _round(book_value * rate)\n if book_value - depreciation < salvage:\n depreciation = _round(book_value - salvage)\n book_value = _round(book_value - depreciation)\n schedule.append({'year': year, 'depreciation': depreciation,\n 'book_value': book_value})\n else:\n raise ValueError(\"method must be 'straight_line' or 'declining_balance'\")\n\n return schedule\n\n\nif __name__ == '__main__':\n print(depreciation_schedule(Decimal('1000.00'), Decimal('100.00'), 3,\n 'straight_line'))\n print(depreciation_schedule(Decimal('1000.00'), Decimal('100.00'), 2,\n 'declining_balance', rate=Decimal('0.40')))"}], "meta": {"idx": 2415, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 842, "latency_s": 8.2}} +{"prompt": [{"role": "user", "content": "Write a function `t_account_balance(entries)` that computes the net balance of a T-account. Each entry is a tuple `(side, amount)` where `side` is either the string 'debit' or 'credit', and `amount` is a string representing a monetary value (e.g. '100.50'). Debits increase the balance, credits decrease it. Use `decimal.Decimal` for exact arithmetic and round the final result to 2 decimal places using `ROUND_HALF_UP`. If the result is negative, return it as-is (a credit balance); if positive, a debit balance. For example, given [('debit', '100.50'), ('credit', '30.25'), ('credit', '70.25')] the function returns Decimal('0.00'), and given [('debit', '100.00'), ('credit', '30.25')] it returns Decimal('69.75')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef t_account_balance(entries):\n total = Decimal('0')\n for side, amount in entries:\n value = Decimal(amount)\n if side == 'debit':\n total += value\n elif side == 'credit':\n total -= value\n else:\n raise ValueError(\"side must be 'debit' or 'credit'\")\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)"}], "meta": {"idx": 2416, "topic": "general ledger and T-account operations", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 296, "latency_s": 3.7}} +{"prompt": [{"role": "user", "content": "You are given a list of ledger transactions for a small business. Each transaction is a dict with fields: 'id' (unique int), 'date' (ISO string), 'account' (str), and 'amount' (str representing a decimal, e.g. '150.00'). Some transactions are marked as reversals: a dict with 'id', 'reverses' (the id of a transaction to reverse), and 'date'. A reversal fully cancels the original transaction by posting an equal-and-opposite amount on the same account and date. Additionally, some transactions may be 'voided': a dict with 'id' and 'voided': True \u2014 these should be ignored entirely, and any reversal pointing at a voided transaction should also be ignored. Write a function `net_balance(transactions, account)` that returns the Decimal net balance of the given account after applying all valid transactions and reversals (voided ones excluded), rounded to 2 decimal places with ROUND_HALF_UP. For example, given transactions [{'id':1,'date':'2024-01-05','account':'cash','amount':'150.00'},{'id':2,'date':'2024-01-06','account':'cash','amount':'-40.25'},{'id':3,'reverses':1,'date':'2024-01-07'},{'id':4,'date':'2024-01-08','account':'cash','amount':'75.00','voided':True}], net_balance(...,'cash') should return Decimal('-40.25'), because txn 1 (+150.00) is reversed by txn 3, txn 2 stands (-40.25), and the voided txn 4 is ignored."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef net_balance(transactions, account):\n by_id = {}\n for t in transactions:\n if 'reverses' in t:\n continue\n if t.get('voided'):\n continue\n by_id[t['id']] = t\n\n voided_ids = {t['id'] for t in transactions if t.get('voided')}\n\n balance = Decimal('0')\n for t in transactions:\n if 'reverses' in t:\n target_id = t['reverses']\n target = by_id.get(target_id)\n if target is None or target_id in voided_ids:\n continue\n if target['account'] != account:\n continue\n balance -= Decimal(target['amount'])\n continue\n if t.get('voided'):\n continue\n if t['account'] == account:\n balance += Decimal(t['amount'])\n\n return balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n txns = [\n {'id': 1, 'date': '2024-01-05', 'account': 'cash', 'amount': '150.00'},\n {'id': 2, 'date': '2024-01-06', 'account': 'cash', 'amount': '-40.25'},\n {'id': 3, 'reverses': 1, 'date': '2024-01-07'},\n {'id': 4, 'date': '2024-01-08', 'account': 'cash', 'amount': '75.00', 'voided': True},\n ]\n print(net_balance(txns, 'cash'))"}], "meta": {"idx": 2410, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 677, "latency_s": 35.2}} +{"prompt": [{"role": "user", "content": "Write a function `quarter_end_report(entries, year)` that produces a fiscal quarter-end summary from a list of bookkeeping entries. Each entry is a tuple `(date_string, account, amount_str)` where `date_string` is ISO format 'YYYY-MM-DD', `account` is a string like 'Revenue' or 'Expenses', and `amount_str` is a decimal string (positive for debit, negative for credit). For the given calendar year, group entries by calendar quarter (Q1: Jan-Mar, Q2: Apr-Jun, Q3: Jul-Sep, Q4: Oct-Dec) and for each quarter compute: (1) the month-end date of the quarter's last month (the 28th for February in a non-leap year, the 29th in a leap year, otherwise the 30th/31st as appropriate), and (2) the running balance of all entries from the start of the year through the last day of that quarter, per account, rounded to 2 decimal places with ROUND_HALF_UP. Return a dict mapping 'Q1'..'Q4' to a dict with keys 'month_end' (a date object) and 'balances' (a dict of account to Decimal balance at quarter end, including every account seen in that quarter with a nonzero net, plus accounts carried forward from earlier quarters). Entries dated outside the given year are ignored. Example: entries = [('2024-03-31','Revenue','100.00'), ('2024-02-28','Expenses','40.505'), ('2023-12-31','Revenue','999.00')], year=2024 gives Q1 = {'month_end': date(2024,3,31), 'balances': {'Revenue': Decimal('100.00'), 'Expenses': Decimal('-40.51')}} because 40.505 rounds to 40.51, and the 2023 entry is ignored; Q2-Q4 have empty balances and their correct month-end dates (2024-06-30, 2024-09-30, 2024-12-31)."}], "completion": [{"role": "assistant", "content": "from datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\nimport calendar\n\n\ndef quarter_end_report(entries, year):\n quarters = {}\n for q in range(1, 5):\n last_month = q * 3\n last_day = calendar.monthrange(year, last_month)[1]\n quarters['Q%d' % q] = {\n 'month_end': date(year, last_month, last_day),\n 'balances': {},\n }\n\n # Sort valid entries by date\n valid = []\n for ds, account, amount in entries:\n d = date.fromisoformat(ds)\n if d.year != year:\n continue\n valid.append((d, account, Decimal(amount)))\n valid.sort(key=lambda e: e[0])\n\n quarter_last_days = [quarters['Q%d' % q]['month_end'] for q in range(1, 5)]\n\n running = {}\n idx = 0\n for q in range(1, 5):\n qend = quarter_last_days[q - 1]\n while idx < len(valid) and valid[idx][0] <= qend:\n _, account, amount = valid[idx]\n running[account] = running.get(account, Decimal('0')) + amount\n idx += 1\n balances = {}\n for account, bal in running.items():\n rounded = bal.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n if rounded != 0:\n balances[account] = rounded\n quarters['Q%d' % q]['balances'] = balances\n\n return quarters\n\n\nif __name__ == '__main__':\n entries = [\n ('2024-03-31', 'Revenue', '100.00'),\n ('2024-02-28', 'Expenses', '40.505'),\n ('2023-12-31', 'Revenue', '999.00'),\n ]\n result = quarter_end_report(entries, 2024)\n print(result)"}], "meta": {"idx": 2412, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 807, "latency_s": 30.7}} +{"prompt": [{"role": "user", "content": "Implement a function `split_into_fiscal_quarters(start_date, end_date, total_amount, fiscal_year_start_month)` that spreads a contract's total fee across the fiscal quarters it spans, in proportion to the number of contract days falling in each quarter (both contract dates inclusive). A fiscal year is labeled with the calendar year in which it ends; e.g., with a July start, the fiscal year running 2024-07-01 through 2025-06-30 is FY2025, and its quarters are Q1=Jul-Sep, Q2=Oct-Dec, Q3=Jan-Mar, Q4=Apr-Jun. For each overlapping quarter return a dict with keys `quarter` (like \"FY2025-Q2\"), `period_start`, `period_end` (ISO date strings, clipped to the contract window), `days` (inclusive day count), and `amount` (a string of a Decimal with exactly two decimal places). Amounts must be computed with `decimal.Decimal` and rounded half-up to cents, and the final quarter must absorb any rounding residual so the amounts sum exactly to the total; `total_amount` may be given as a string like \"10000.00\". Worked example: start 2024-11-15, end 2025-02-10, total \"10000.00\", fiscal year starting in July \u2014 the contract has 88 days, 47 in FY2025-Q2 (2024-11-15 to 2024-12-31) and 41 in FY2025-Q3 (2025-01-01 to 2025-02-10), so the output is [{'quarter': 'FY2025-Q2', 'period_start': '2024-11-15', 'period_end': '2024-12-31', 'days': 47, 'amount': '5340.91'}, {'quarter': 'FY2025-Q3', 'period_start': '2025-01-01', 'period_end': '2025-02-10', 'days': 41, 'amount': '4659.09'}]. The solution must use only the standard library and must also work when the fiscal year starts in January (fiscal year = calendar year) and when the contract spans multiple fiscal years."}], "completion": [{"role": "assistant", "content": "from calendar import monthrange\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\ndef month_end(year, month):\n \"\"\"Return the last day of the given month as a date.\"\"\"\n return date(year, month, monthrange(year, month)[1])\n\n\ndef add_months(year, month, k):\n \"\"\"Shift (year, month) forward by k months, wrapping years.\"\"\"\n t = month - 1 + k\n return year + t // 12, t % 12 + 1\n\n\ndef fiscal_quarter_of(d, fysm):\n \"\"\"Return (fiscal_year_label, quarter_number) for date d,\n where the fiscal year is labeled by the calendar year in which it ends.\"\"\"\n if fysm == 1:\n fy, offset = d.year, d.month - 1\n elif d.month >= fysm:\n fy, offset = d.year + 1, d.month - fysm\n else:\n fy, offset = d.year, d.month - fysm + 12\n return fy, offset // 3 + 1\n\n\ndef quarter_bounds(fy, q, fysm):\n \"\"\"Return (start_date, end_date) of quarter q of fiscal year FY fy.\"\"\"\n base_year = fy if fysm == 1 else fy - 1\n sy, sm = add_months(base_year, fysm, 3 * (q - 1))\n ey, em = add_months(sy, sm, 2)\n return date(sy, sm, 1), month_end(ey, em)\n\n\ndef split_into_fiscal_quarters(start_date, end_date, total_amount,\n fiscal_year_start_month):\n fysm = fiscal_year_start_month\n if not (1 <= fysm <= 12):\n raise ValueError(\"fiscal_year_start_month must be an integer 1..12\")\n if end_date < start_date:\n raise ValueError(\"end_date must not precede start_date\")\n\n total = Decimal(str(total_amount)).quantize(CENT, rounding=ROUND_HALF_UP)\n total_days = (end_date - start_date).days + 1\n\n entries = []\n fy, q = fiscal_quarter_of(start_date, fysm)\n q_start, q_end = quarter_bounds(fy, q, fysm)\n while q_start <= end_date:\n p_start = max(start_date, q_start)\n p_end = min(end_date, q_end)\n days = (p_end - p_start).days + 1\n entries.append({\n \"quarter\": \"FY{}-Q{}\".format(fy, q),\n \"period_start\": p_start.isoformat(),\n \"period_end\": p_end.isoformat(),\n \"days\": days,\n })\n q += 1\n if q > 4:\n q, fy = 1, fy + 1\n q_start, q_end = quarter_bounds(fy, q, fysm)\n\n allocated = Decimal(\"0.00\")\n n = len(entries)\n for i, entry in enumerate(entries):\n if i < n - 1:\n amt = (total * entry[\"days\"] / total_days).quantize(\n CENT, rounding=ROUND_HALF_UP)\n else:\n # Final quarter absorbs the rounding residual.\n amt = total - allocated\n entry[\"amount\"] = str(amt)\n allocated += amt\n\n if allocated != total:\n raise AssertionError(\"allocations do not sum to the total\")\n return entries\n\n\nif __name__ == \"__main__\":\n # Worked example from the statement.\n result = split_into_fiscal_quarters(\n date(2024, 11, 15), date(2025, 2, 10), \"10000.00\", 7)\n for e in result:\n print(e)\n print(\"Sum:\", sum(Decimal(e[\"amount\"]) for e in result))\n\n # Extra checks: January fiscal year and a multi-year contract.\n r2 = split_into_fiscal_quarters(\n date(2024, 12, 1), date(2025, 1, 31), \"999.99\", 1)\n for e in r2:\n print(e)\n assert sum(Decimal(e[\"amount\"]) for e in r2) == Decimal(\"999.99\")\n\n r3 = split_into_fiscal_quarters(\n date(2024, 5, 10), date(2026, 8, 20), \"12345.67\", 7)\n assert sum(Decimal(e[\"amount\"]) for e in r3) == Decimal(\"12345.67\")\n assert r3[0][\"quarter\"] == \"FY2025-Q4\"\n assert r3[-1][\"quarter\"] == \"FY2027-Q1\"\n print(\"All checks passed.\")"}], "meta": {"idx": 2394, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1357, "latency_s": 91.1}} +{"prompt": [{"role": "user", "content": "You are given a dictionary containing accounts receivable invoices (customers) and accounts payable invoices (vendors), plus payment records for each side; every invoice has invoice_id, entity, amount, invoice_date, and due_date, every payment has entity, amount, and date, and all money values are strings that must be parsed as Decimal (never float). Apply payments per entity using FIFO: sort the entity's invoices by (invoice_date, invoice_id), then apply each payment (processed in date order) to the oldest invoice's remaining balance first, carrying any leftover to the next invoice; if a payment exceeds all open invoices for that entity, the excess becomes a credit that reduces the entity's 'current' bucket (possibly making it negative). Against the given report_date, each invoice's remaining balance falls into an aging bucket by days past due, computed as (report_date - due_date).days clamped at a minimum of 0: 'current' (<=0), '1-30', '31-60', '61-90', 'over_90'; additionally compute avg_age_days = (sum of remaining x days_past_due) / total_balance, rounded half-up to 2 decimals (0.00 when balance <= 0). The report must map each entity (sorted alphabetically) plus a '_total' row for each side to an object with balance, current, 1-30, 31-60, 61-90, over_90, and avg_age_days, where every monetary value is a string quantized to 2 decimal places with ROUND_HALF_UP, and it must include a top-level 'net_position' equal to the AR total minus the AP total. For example, with report_date '2024-04-15', AR invoices INV-1 (Acme, 100.00, due 2024-01-31) and INV-2 (Acme, 250.50, due 2024-03-11) and INV-3 (Beta, 80.25, due 2024-05-20), an AR payment of 150.00 from Acme, and an AP invoice BILL-1 (SupplyCo, 500.00, due 2024-02-14) with no payments: the 150.00 fully pays INV-1 and leaves 200.00 on INV-2, which is 35 days past due, so Acme reports balance '200.00' with '200.00' in '31-60' and avg_age_days '35.00', Beta reports '80.25' all in 'current' with avg_age_days '0.00', the AR '_total' row shows balance '280.25', current '80.25', '31-60' '200.00', and avg_age_days '24.98' (since 200x35/280.25 = 24.9777... rounds to 24.98), SupplyCo shows '500.00' in '61-90' (61 days past due) with avg_age_days '61.00', and net_position is '-219.75'. Write a function aging_report(data) that returns this report as a plain dict."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nTWO_PLACES = Decimal(\"0.01\")\nBUCKETS = [\"current\", \"1-30\", \"31-60\", \"61-90\", \"over_90\"]\n\n\ndef _q(value):\n \"\"\"Quantize a Decimal to 2 places using round-half-up.\"\"\"\n return value.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\n\ndef _bucket_for(days_past_due):\n if days_past_due <= 0:\n return \"current\"\n if days_past_due <= 30:\n return \"1-30\"\n if days_past_due <= 60:\n return \"31-60\"\n if days_past_due <= 90:\n return \"61-90\"\n return \"over_90\"\n\n\ndef _apply_payments(invoices, payments):\n \"\"\"FIFO-apply payments to invoices per entity.\n\n Returns (by_entity, remaining, credits) where by_entity maps entity to\n its invoice list sorted oldest-first, remaining maps invoice_id to its\n unpaid Decimal balance, and credits maps entity to any overpayment.\n \"\"\"\n by_entity = {}\n for inv in invoices:\n by_entity.setdefault(inv[\"entity\"], []).append(inv)\n for invs in by_entity.values():\n invs.sort(key=lambda i: (i[\"invoice_date\"], i[\"invoice_id\"]))\n\n remaining = {inv[\"invoice_id\"]: Decimal(inv[\"amount\"]) for inv in invoices}\n credits = {}\n\n for pay in sorted(payments, key=lambda p: (p[\"date\"], p[\"entity\"])):\n entity = pay[\"entity\"]\n amount = Decimal(pay[\"amount\"])\n credit = credits.get(entity, Decimal(\"0\"))\n\n # Consume any existing credit for this entity first.\n if credit > 0:\n use = credit if credit < amount else amount\n credit -= use\n amount -= use\n\n # FIFO against the oldest open invoices.\n for inv in by_entity.get(entity, []):\n if amount <= 0:\n break\n open_amt = remaining[inv[\"invoice_id\"]]\n applied = open_amt if open_amt < amount else amount\n remaining[inv[\"invoice_id\"]] = open_amt - applied\n amount -= applied\n\n # Any leftover is an overpayment (credit) for this entity.\n credits[entity] = credit + amount\n\n return by_entity, remaining, credits\n\n\ndef _build_side(invoices, payments, report_date_str):\n \"\"\"Build the aging report for one side (AR or AP).\"\"\"\n report_date = date.fromisoformat(report_date_str)\n by_entity, remaining, credits = _apply_payments(invoices, payments)\n\n side = {}\n grand = {b: Decimal(\"0\") for b in BUCKETS}\n grand_total = Decimal(\"0\")\n grand_weighted = Decimal(\"0\")\n\n for entity in sorted(by_entity):\n buckets = {b: Decimal(\"0\") for b in BUCKETS}\n total = Decimal(\"0\")\n weighted = Decimal(\"0\")\n\n for inv in by_entity[entity]:\n rem = remaining[inv[\"invoice_id\"]]\n if rem == 0:\n continue\n dpd = (report_date - date.fromisoformat(inv[\"due_date\"])).days\n if dpd < 0:\n dpd = 0\n buckets[_bucket_for(dpd)] += rem\n total += rem\n weighted += rem * dpd\n\n # Overpayment credit reduces the current bucket (may go negative).\n credit = credits.get(entity, Decimal(\"0\"))\n if credit > 0:\n buckets[\"current\"] -= credit\n total -= credit\n\n avg = _q(weighted / total) if total > 0 else Decimal(\"0.00\")\n\n row = {\"balance\": str(_q(total))}\n for b in BUCKETS:\n row[b] = str(_q(buckets[b]))\n row[\"avg_age_days\"] = str(avg)\n side[entity] = row\n\n for b in BUCKETS:\n grand[b] += buckets[b]\n grand_total += total\n grand_weighted += weighted\n\n total_avg = _q(grand_weighted / grand_total) if grand_total > 0 else Decimal(\"0.00\")\n total_row = {\"balance\": str(_q(grand_total))}\n for b in BUCKETS:\n total_row[b] = str(_q(grand[b]))\n total_row[\"avg_age_days\"] = str(total_avg)\n side[\"_total\"] = total_row\n\n return side, _q(grand_total)\n\n\ndef aging_report(data):\n \"\"\"Produce AR/AP aging report from raw invoice and payment data.\"\"\"\n ar_side, ar_total = _build_side(\n data.get(\"ar\", []), data.get(\"ar_payments\", []), data[\"report_date\"]\n )\n ap_side, ap_total = _build_side(\n data.get(\"ap\", []), data.get(\"ap_payments\", []), data[\"report_date\"]\n )\n return {\n \"accounts_receivable\": ar_side,\n \"accounts_payable\": ap_side,\n \"net_position\": str(_q(ar_total - ap_total)),\n }\n\n\nif __name__ == \"__main__\":\n example = {\n \"report_date\": \"2024-04-15\",\n \"ar\": [\n {\"invoice_id\": \"INV-1\", \"entity\": \"Acme\", \"amount\": \"100.00\",\n \"invoice_date\": \"2024-01-01\", \"due_date\": \"2024-01-31\"},\n {\"invoice_id\": \"INV-2\", \"entity\": \"Acme\", \"amount\": \"250.50\",\n \"invoice_date\": \"2024-02-10\", \"due_date\": \"2024-03-11\"},\n {\"invoice_id\": \"INV-3\", \"entity\": \"Beta\", \"amount\": \"80.25\",\n \"invoice_date\": \"2024-03-20\", \"due_date\": \"2024-05-20\"},\n ],\n \"ar_payments\": [\n {\"entity\": \"Acme\", \"amount\": \"150.00\", \"date\": \"2024-03-01\"},\n ],\n \"ap\": [\n {\"invoice_id\": \"BILL-1\", \"entity\": \"SupplyCo\", \"amount\": \"500.00\",\n \"invoice_date\": \"2024-01-15\", \"due_date\": \"2024-02-14\"},\n ],\n \"ap_payments\": [],\n }\n\n result = aging_report(example)\n\n assert result[\"accounts_receivable\"][\"Acme\"] == {\n \"balance\": \"200.00\", \"current\": \"0.00\", \"1-30\": \"0.00\",\n \"31-60\": \"200.00\", \"61-90\": \"0.00\", \"over_90\": \"0.00\",\n \"avg_age_days\": \"35.00\",\n }\n assert result[\"accounts_receivable\"][\"_total\"][\"avg_age_days\"] == \"24.98\"\n assert result[\"accounts_payable\"][\"SupplyCo\"][\"61-90\"] == \"500.00\"\n assert result[\"net_position\"] == \"-219.75\"\n\n import json\n print(json.dumps(result, indent=2))"}], "meta": {"idx": 2406, "topic": "accounts receivable and payable aging reports", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2139, "latency_s": 65.3}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts (a dict mapping each account code to a tuple (name, type), where type is one of 'asset', 'liability', 'equity', 'revenue', 'expense') and a general journal (a list of transactions, each a dict {\"id\": ..., \"lines\": [(code, debit_str, credit_str), ...]} where amounts are strings that may carry more than two decimal places). Write a function summarize_ledger(accounts, transactions) that first rounds every line amount to cents using Decimal with ROUND_HALF_UP, raises ValueError for unknown account codes, negative amounts, or any transaction whose total debits do not equal total credits (message must include the transaction id, e.g. 'unbalanced transaction T3'), and then produces a report. The report must contain: (1) 'trial_balance', mapping every account code in the chart to its name, type, and its net balance expressed as a rounded 'debit' or 'credit' figure; (2) 'net_income', the total of revenue accounts (credit-minus-debit) minus the total of expense accounts (debit-minus-credit), rounded to cents; (3) 'balance_sheet' with 'assets' (sum of asset accounts' debit-minus-credit), 'liabilities' (credit-minus-debit), 'equity' (stated equity accounts' credit-minus-debit plus net_income for the current period), and 'balanced', a boolean that is True iff assets == liabilities + equity. For example, with accounts {\"100\": (\"Cash\",\"asset\"), \"200\": (\"Accounts Payable\",\"liability\"), \"300\": (\"Owner's Equity\",\"equity\"), \"400\": (\"Sales\",\"revenue\"), \"500\": (\"Rent Expense\",\"expense\")} and transactions T1=[(\"100\",\"5000.00\",\"0\"),(\"300\",\"0\",\"5000.00\")], T2=[(\"500\",\"1200.00\",\"0\"),(\"100\",\"0\",\"1200.00\")], T3=[(\"100\",\"2000.00\",\"0\"),(\"400\",\"0\",\"2000.00\")], the function must return net_income = 800.00, assets = 5800.00, liabilities = 0.00, equity = 5800.00, and balanced = True."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0\")\n\nVALID_TYPES = {\"asset\", \"liability\", \"equity\", \"revenue\", \"expense\"}\n\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef summarize_ledger(accounts, transactions):\n \"\"\"\n Summarize a general journal into trial-balance, P&L, and\n balance-sheet figures.\n\n accounts: dict mapping code -> (name, type), type in VALID_TYPES.\n transactions: list of {\"id\": ..., \"lines\": [(code, debit, credit), ...]}\n where debit/credit are string amounts.\n \"\"\"\n for code, info in accounts.items():\n if len(info) != 2 or info[1] not in VALID_TYPES:\n raise ValueError(f\"invalid account definition for code {code!r}\")\n\n debit_totals = defaultdict(lambda: ZERO)\n credit_totals = defaultdict(lambda: ZERO)\n\n for txn in transactions:\n txn_id = txn.get(\"id\")\n txn_debits = ZERO\n txn_credits = ZERO\n for code, debit_str, credit_str in txn[\"lines\"]:\n if code not in accounts:\n raise ValueError(f\"unknown account code: {code}\")\n debit = _round_cents(Decimal(str(debit_str)))\n credit = _round_cents(Decimal(str(credit_str)))\n if debit < ZERO or credit < ZERO:\n raise ValueError(f\"negative amount in transaction {txn_id}\")\n debit_totals[code] += debit\n credit_totals[code] += credit\n txn_debits += debit\n txn_credits += credit\n if txn_debits != txn_credits:\n raise ValueError(f\"unbalanced transaction {txn_id}\")\n\n trial_balance = {}\n assets_total = ZERO\n liabilities_total = ZERO\n stated_equity = ZERO\n revenue_total = ZERO\n expense_total = ZERO\n\n for code in sorted(accounts, key=str):\n name, acct_type = accounts[code]\n net = debit_totals[code] - credit_totals[code]\n debit_side = net if net > ZERO else ZERO\n credit_side = -net if net < ZERO else ZERO\n trial_balance[code] = {\n \"name\": name,\n \"type\": acct_type,\n \"debit\": _round_cents(debit_side),\n \"credit\": _round_cents(credit_side),\n }\n if acct_type == \"asset\":\n assets_total += net\n elif acct_type == \"liability\":\n liabilities_total += -net\n elif acct_type == \"equity\":\n stated_equity += -net\n elif acct_type == \"revenue\":\n revenue_total += -net\n else: # expense\n expense_total += net\n\n net_income = _round_cents(revenue_total - expense_total)\n assets_total = _round_cents(assets_total)\n liabilities_total = _round_cents(liabilities_total)\n equity_total = _round_cents(stated_equity + net_income)\n\n balance_sheet = {\n \"assets\": assets_total,\n \"liabilities\": liabilities_total,\n \"equity\": equity_total,\n \"balanced\": assets_total == liabilities_total + equity_total,\n }\n\n return {\n \"trial_balance\": trial_balance,\n \"net_income\": net_income,\n \"balance_sheet\": balance_sheet,\n }\n\n\nif __name__ == \"__main__\":\n accounts = {\n \"100\": (\"Cash\", \"asset\"),\n \"200\": (\"Accounts Payable\", \"liability\"),\n \"300\": (\"Owner's Equity\", \"equity\"),\n \"400\": (\"Sales\", \"revenue\"),\n \"500\": (\"Rent Expense\", \"expense\"),\n }\n transactions = [\n {\"id\": \"T1\", \"lines\": [(\"100\", \"5000.00\", \"0\"), (\"300\", \"0\", \"5000.00\")]},\n {\"id\": \"T2\", \"lines\": [(\"500\", \"1200.00\", \"0\"), (\"100\", \"0\", \"1200.00\")]},\n {\"id\": \"T3\", \"lines\": [(\"100\", \"2000.00\", \"0\"), (\"400\", \"0\", \"2000.00\")]},\n ]\n\n report = summarize_ledger(accounts, transactions)\n\n print(\"Trial balance:\")\n for code, row in report[\"trial_balance\"].items():\n print(f\" {code} {row['name']:<20} type={row['type']:<10} \"\n f\"debit={row['debit']} credit={row['credit']}\")\n print(\"Net income: \", report[\"net_income\"])\n print(\"Balance sheet:\")\n bs = report[\"balance_sheet\"]\n print(\" assets =\", bs[\"assets\"])\n print(\" liabilities =\", bs[\"liabilities\"])\n print(\" equity =\", bs[\"equity\"])\n print(\" balanced =\", bs[\"balanced\"])\n\n assert report[\"net_income\"] == Decimal(\"800.00\")\n assert bs[\"assets\"] == Decimal(\"5800.00\")\n assert bs[\"liabilities\"] == Decimal(\"0.00\")\n assert bs[\"equity\"] == Decimal(\"5800.00\")\n assert bs[\"balanced\"] is True\n\n bad = [\n {\"id\": \"T9\", \"lines\": [(\"100\", \"10.00\", \"0\"), (\"400\", \"0\", \"9.99\")]},\n ]\n try:\n summarize_ledger(accounts, bad)\n raise AssertionError(\"expected ValueError\")\n except ValueError as exc:\n assert \"unbalanced transaction T9\" in str(exc)\n print(\"Validation OK:\", exc)"}], "meta": {"idx": 2383, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1773, "latency_s": 137.8}} +{"prompt": [{"role": "user", "content": "Write a program that processes a sales ledger and produces a VAT report. Input is a list of invoice entries, each given as a tuple (invoice_id, net_amount_str, vat_rate_str), where net_amount_str is a decimal string like '100.00' and vat_rate_str is a rate like '0.20' for 20% or '0.05' for 5%. For each entry, compute the VAT amount as net * rate, rounded half-up to 2 decimal places using Decimal arithmetic (never use float). Output a report as a list of tuples (invoice_id, net, vat, gross) and the totals: total net, total VAT, and total gross, each also rounded half-up to 2 decimals. All monetary values must be quantized with ROUND_HALF_UP. Example: entries [('A1', '100.00', '0.20'), ('B2', '3.33', '0.05')] yield [('A1', Decimal('100.00'), Decimal('20.00'), Decimal('120.00')), ('B2', Decimal('3.33'), Decimal('0.17'), Decimal('3.50'))] with totals net 103.33, VAT 20.17, gross 123.50. The function must be named build_vat_report(entries) and return (report_lines, total_net, total_vat, total_gross)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _money(value):\n return Decimal(value).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef build_vat_report(entries):\n report_lines = []\n total_net = Decimal('0.00')\n total_vat = Decimal('0.00')\n total_gross = Decimal('0.00')\n\n for invoice_id, net_str, rate_str in entries:\n net = Decimal(net_str)\n rate = Decimal(rate_str)\n vat = _money(net * rate)\n gross = _money(net + vat)\n report_lines.append((invoice_id, _money(net), vat, gross))\n total_net += _money(net)\n total_vat += vat\n total_gross += gross\n\n return report_lines, _money(total_net), _money(total_vat), _money(total_gross)\n\n\nif __name__ == '__main__':\n entries = [('A1', '100.00', '0.20'), ('B2', '3.33', '0.05')]\n lines, net, vat, gross = build_vat_report(entries)\n for line in lines:\n print(line)\n print('Totals: net=%s vat=%s gross=%s' % (net, vat, gross))"}], "meta": {"idx": 2421, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 514, "latency_s": 6.4}} +{"prompt": [{"role": "user", "content": "Write a function `accrual_report(transactions, balances, period)` that converts a cash-basis transaction ledger into an accrual-basis income statement for a fiscal period, using only the standard library and `decimal.Decimal` for all money math (round every reported figure to cents with `ROUND_HALF_UP`). Each transaction is a dict with keys `\"date\"` (ISO `YYYY-MM-DD` string), `\"type\"` (`\"receipt\"` or `\"disbursement\"`), `\"category\"`, and `\"amount\"` (a string like `\"12000.00\"`); transactions dated outside the inclusive period `period[\"start\"]`..`period[\"end\"]` are ignored, and any unknown `type`, unknown `category`, or negative amount must raise `ValueError`. Valid receipt categories are `customer`, `owner_contribution`, `loan_proceeds` (only `customer` is revenue); valid disbursement categories are `supplier`, `rent`, `wages`, `equipment_purchase` (equipment purchases are capital outlays, never an expense). The `balances` dict provides beginning/ending balances (as strings) for `accounts_receivable`, `accounts_payable`, `unearned_revenue`, `prepaid_expenses`, plus a `depreciation_expense` amount. Accrual revenue = customer cash receipts + (AR ending \u2212 AR beginning) \u2212 (unearned ending \u2212 unearned beginning); supplier expense = supplier cash paid + (AP ending \u2212 AP beginning); insurance expense = prepaid beginning \u2212 prepaid ending; rent and wages equal their cash paid. The function must return a dict with keys `revenue`, `total_expenses`, `net_income` (revenue \u2212 total expenses), `cash_basis_net_income` (customer receipts \u2212 supplier/rent/wage disbursements), and `accrual_adjustments_total` (`net_income` \u2212 `cash_basis_net_income`), all `Decimal` values in cents. Worked example: for period 2024-01-01 to 2024-12-31, transactions = customer receipt 12000.00, owner contribution 500.00, supplier disbursement 6000.00, rent 1200.00, wages 3000.00, equipment 2000.00; balances AR 1500.00\u21922500.00, AP 800.00\u2192400.00, unearned 300.00\u2192900.00, prepaid 200.00\u2192150.00, depreciation 250.00; the result is revenue 12400.00, total expenses 10100.00, net income 2300.00, cash-basis net income 1800.00, and accrual adjustments total 500.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nCENT = Decimal(\"0.01\")\n\nVALID_RECEIPT_CATEGORIES = {\"customer\", \"owner_contribution\", \"loan_proceeds\"}\nVALID_DISBURSEMENT_CATEGORIES = {\"supplier\", \"rent\", \"wages\", \"equipment_purchase\"}\nOPERATING_EXPENSE_CATEGORIES = {\"supplier\", \"rent\", \"wages\"}\n\n\ndef _to_date(s, label):\n try:\n y, m, d = s.split(\"-\")\n return date(int(y), int(m), int(d))\n except (ValueError, AttributeError):\n raise ValueError(f\"invalid {label} date: {s!r}\")\n\n\ndef _to_money(s, label):\n try:\n value = Decimal(s)\n except Exception:\n raise ValueError(f\"invalid {label} amount: {s!r}\")\n if value < 0:\n raise ValueError(f\"negative {label} amount: {s!r}\")\n return value\n\n\ndef _balance_pair(balances, key):\n if key not in balances:\n raise ValueError(f\"missing balance: {key}\")\n pair = balances[key]\n try:\n beg = Decimal(pair[\"beginning\"])\n end = Decimal(pair[\"ending\"])\n except Exception:\n raise ValueError(f\"invalid balances for {key}\")\n if beg < 0 or end < 0:\n raise ValueError(f\"negative balance for {key}\")\n return beg, end\n\n\ndef accrual_report(transactions, balances, period):\n start = _to_date(period[\"start\"], \"period start\")\n end = _to_date(period[\"end\"], \"period end\")\n if start > end:\n raise ValueError(\"period start is after period end\")\n\n cash_customer = Decimal(\"0\")\n cash_by_expense = {c: Decimal(\"0\") for c in OPERATING_EXPENSE_CATEGORIES}\n\n for txn in transactions:\n txn_date = _to_date(txn[\"date\"], \"transaction\")\n if txn_date < start or txn_date > end:\n continue\n amount = _to_money(txn[\"amount\"], \"transaction\")\n txn_type = txn[\"type\"]\n category = txn[\"category\"]\n\n if txn_type == \"receipt\":\n if category not in VALID_RECEIPT_CATEGORIES:\n raise ValueError(f\"unknown receipt category: {category!r}\")\n if category == \"customer\":\n cash_customer += amount\n elif txn_type == \"disbursement\":\n if category not in VALID_DISBURSEMENT_CATEGORIES:\n raise ValueError(f\"unknown disbursement category: {category!r}\")\n if category in OPERATING_EXPENSE_CATEGORIES:\n cash_by_expense[category] += amount\n else:\n raise ValueError(f\"unknown transaction type: {txn_type!r}\")\n\n ar_beg, ar_end = _balance_pair(balances, \"accounts_receivable\")\n ap_beg, ap_end = _balance_pair(balances, \"accounts_payable\")\n ur_beg, ur_end = _balance_pair(balances, \"unearned_revenue\")\n pp_beg, pp_end = _balance_pair(balances, \"prepaid_expenses\")\n\n if \"depreciation_expense\" not in balances:\n raise ValueError(\"missing depreciation_expense\")\n depreciation = _to_money(balances[\"depreciation_expense\"], \"depreciation\")\n\n revenue = cash_customer + (ar_end - ar_beg) - (ur_end - ur_beg)\n supplier_expense = cash_by_expense[\"supplier\"] + (ap_end - ap_beg)\n rent_expense = cash_by_expense[\"rent\"]\n wage_expense = cash_by_expense[\"wages\"]\n insurance_expense = pp_beg - pp_end\n\n total_expenses = (\n supplier_expense + rent_expense + wage_expense + insurance_expense + depreciation\n )\n net_income = revenue - total_expenses\n\n cash_operating_outflows = sum(cash_by_expense.values(), Decimal(\"0\"))\n cash_basis_net_income = cash_customer - cash_operating_outflows\n\n q = lambda v: v.quantize(CENT, rounding=ROUND_HALF_UP)\n revenue_q = q(revenue)\n total_expenses_q = q(total_expenses)\n net_income_q = q(net_income)\n cash_basis_q = q(cash_basis_net_income)\n\n return {\n \"revenue\": revenue_q,\n \"total_expenses\": total_expenses_q,\n \"net_income\": net_income_q,\n \"cash_basis_net_income\": cash_basis_q,\n \"accrual_adjustments_total\": net_income_q - cash_basis_q,\n }\n\n\nif __name__ == \"__main__\":\n transactions = [\n {\"date\": \"2024-03-15\", \"type\": \"receipt\", \"category\": \"customer\", \"amount\": \"12000.00\"},\n {\"date\": \"2024-04-02\", \"type\": \"receipt\", \"category\": \"owner_contribution\", \"amount\": \"500.00\"},\n {\"date\": \"2024-06-10\", \"type\": \"disbursement\", \"category\": \"supplier\", \"amount\": \"6000.00\"},\n {\"date\": \"2024-07-01\", \"type\": \"disbursement\", \"category\": \"rent\", \"amount\": \"1200.00\"},\n {\"date\": \"2024-09-20\", \"type\": \"disbursement\", \"category\": \"wages\", \"amount\": \"3000.00\"},\n {\"date\": \"2024-10-05\", \"type\": \"disbursement\", \"category\": \"equipment_purchase\", \"amount\": \"2000.00\"},\n {\"date\": \"2023-12-31\", \"type\": \"receipt\", \"category\": \"customer\", \"amount\": \"999.00\"},\n ]\n balances = {\n \"accounts_receivable\": {\"beginning\": \"1500.00\", \"ending\": \"2500.00\"},\n \"accounts_payable\": {\"beginning\": \"800.00\", \"ending\": \"400.00\"},\n \"unearned_revenue\": {\"beginning\": \"300.00\", \"ending\": \"900.00\"},\n \"prepaid_expenses\": {\"beginning\": \"200.00\", \"ending\": \"150.00\"},\n \"depreciation_expense\": \"250.00\",\n }\n period = {\"start\": \"2024-01-01\", \"end\": \"2024-12-31\"}\n report = accrual_report(transactions, balances, period)\n for key, value in report.items():\n print(f\"{key}: {value}\")\n assert report == {\n \"revenue\": Decimal(\"12400.00\"),\n \"total_expenses\": Decimal(\"10100.00\"),\n \"net_income\": Decimal(\"2300.00\"),\n \"cash_basis_net_income\": Decimal(\"1800.00\"),\n \"accrual_adjustments_total\": Decimal(\"500.00\"),\n }"}], "meta": {"idx": 2396, "topic": "accrual versus cash basis adjustments", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2028, "latency_s": 98.3}} +{"prompt": [{"role": "user", "content": "A bookkeeper needs to generate a loan repayment schedule using the actuarial (French) method. Given a loan principal P (a Decimal, in cents-precision), an annual nominal interest rate r (e.g. 0.05 for 5%), and a number of monthly payments n, compute the constant monthly payment A using the standard annuity formula A = P * i / (1 - (1+i)^(-n)) where i = r/12 is the monthly rate. Round A to 2 decimal places with ROUND_HALF_UP. Then build the amortization schedule: for each month, interest = round(balance * i, 2), principal = A - interest, and the running balance decreases accordingly; on the final payment, adjust the principal so the balance becomes exactly 0.00. Return a list of dictionaries, each with keys 'payment', 'interest', 'principal', 'balance' (all Decimal, rounded to 2 places), and the total interest paid over the schedule. Example: P = 10000.00, r = 0.05, n = 12 gives monthly payment 856.07 and total interest 272.29. Write a function amortize(principal: str, annual_rate: str, months: int) that takes the principal and rate as strings (to preserve precision) and returns (schedule, total_interest)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef r2(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef amortize(principal: str, annual_rate: str, months: int):\n P = Decimal(principal)\n r = Decimal(annual_rate)\n i = r / Decimal(12)\n n = months\n if n <= 0:\n return [], Decimal('0.00')\n if i == 0:\n A = r2(P / Decimal(n))\n else:\n A = r2(P * i / (Decimal(1) - (Decimal(1) + i) ** (-n)))\n schedule = []\n balance = P\n total_interest = Decimal('0.00')\n for month in range(1, n + 1):\n interest = r2(balance * i)\n if month == n:\n principal_part = balance\n payment = principal_part + interest\n else:\n principal_part = A - interest\n payment = A\n balance = balance - principal_part\n if month == n:\n balance = Decimal('0.00')\n schedule.append({\n 'payment': r2(payment),\n 'interest': r2(interest),\n 'principal': r2(principal_part),\n 'balance': r2(balance),\n })\n total_interest += r2(interest)\n return schedule, r2(total_interest)\n\nif __name__ == '__main__':\n sched, total = amortize('10000.00', '0.05', 12)\n for row in sched:\n print(row)\n print('Total interest:', total)"}], "meta": {"idx": 2422, "topic": "interest calculation and payment schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 629, "latency_s": 6.4}} +{"prompt": [{"role": "user", "content": "A bookkeeper needs to build a simple amortization report for a small loan. Write a function `build_schedule(principal, annual_rate, months)` that takes the loan principal (a Decimal or string), the nominal annual interest rate as a percentage (e.g. '12' meaning 12% per year), and the number of monthly payments. The loan uses equal monthly payments (annuity) computed with the formula payment = principal * r / (1 - (1+r)**(-n)), where r is the monthly rate (annual rate / 12 / 100). The payment must be rounded to 2 decimal places with ROUND_HALF_UP, and the final payment must be adjusted so the ending balance is exactly zero. The function should return a list of dictionaries, each with keys 'month', 'payment', 'interest', 'principal_paid', 'balance' (all money values as Decimal rounded to 2 places). Interest each month is balance * r rounded to 2 places with ROUND_HALF_UP, and principal_paid = payment - interest, except the last month where payment = remaining balance + interest. Example: principal '1000.00', annual rate '12', months 3 -> monthly rate 0.01, payments of 340.02, 340.02, and 339.99 (approximately), with the final balance exactly 0.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _round(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef build_schedule(principal, annual_rate, months):\n principal = Decimal(str(principal))\n annual_rate = Decimal(str(annual_rate))\n r = annual_rate / Decimal('100') / Decimal('12')\n n = int(months)\n\n if n <= 0:\n return []\n if r == 0:\n base_payment = _round(principal / n)\n else:\n base_payment = _round(principal * r / (Decimal('1') - (Decimal('1') + r) ** (-n)))\n\n schedule = []\n balance = principal\n for month in range(1, n + 1):\n interest = _round(balance * r)\n if month == n:\n payment = _round(balance + interest)\n else:\n payment = base_payment\n principal_paid = payment - interest\n balance = balance - principal_paid\n schedule.append({\n 'month': month,\n 'payment': payment,\n 'interest': interest,\n 'principal_paid': _round(principal_paid),\n 'balance': _round(balance),\n })\n return schedule\n\nif __name__ == '__main__':\n for row in build_schedule('1000.00', '12', 3):\n print(row)"}], "meta": {"idx": 2424, "topic": "interest calculation and payment schedules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 614, "latency_s": 9.8}} +{"prompt": [{"role": "user", "content": "A petty cash fund is maintained with a fixed imprest amount of $300.00. Each transaction is either a disbursement (money paid out, recorded with an expense category) or a replenishment (money added back to restore the fund). Disbursements are recorded as they occur and the cash-on-hand decreases immediately; replenishments arrive only when explicitly requested. Write a program that processes a list of transactions and produces: (1) the current cash-on-hand, (2) a per-category expense report, and (3) the replenishment amount needed to restore the fund to the imprest level (imprest minus cash-on-hand, or $0.00 if cash-on-hand is at or above imprest). All money must be handled with Decimal, quantized to cents with ROUND_HALF_UP. Input is a list of tuples: ('disburse', category, amount) or ('replenish', amount). For example, given transactions [('disburse', 'office supplies', '12.50'), ('disburse', 'postage', '8.25'), ('disburse', 'office supplies', '3.75'), ('replenish', '25.00'), ('disburse', 'meals', '15.00')], cash-on-hand should be 300.00 - 12.50 - 8.25 - 3.75 + 25.00 - 15.00 = 285.50, the category report should be {'office supplies': 16.25, 'postage': 8.25, 'meals': 15.00}, and the required replenishment should be 14.50. Print each value on its own line, with the category report as 'category: amount' lines sorted alphabetically by category."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef money(value):\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef process_petty_cash(transactions, imprest=Decimal('300.00')):\n imprest = money(imprest)\n cash_on_hand = imprest\n categories = {}\n for txn in transactions:\n kind = txn[0]\n if kind == 'disburse':\n _, category, amount = txn\n amount = money(amount)\n cash_on_hand -= amount\n categories[category] = categories.get(category, Decimal('0.00')) + amount\n elif kind == 'replenish':\n amount = money(txn[1])\n cash_on_hand += amount\n else:\n raise ValueError('Unknown transaction type: {}'.format(kind))\n cash_on_hand = money(cash_on_hand)\n shortfall = imprest - cash_on_hand\n replenishment = shortfall if shortfall > 0 else Decimal('0.00')\n replenishment = money(replenishment)\n report = {cat: money(total) for cat, total in categories.items()}\n return cash_on_hand, report, replenishment\n\n\ndef main():\n transactions = [\n ('disburse', 'office supplies', '12.50'),\n ('disburse', 'postage', '8.25'),\n ('disburse', 'office supplies', '3.75'),\n ('replenish', '25.00'),\n ('disburse', 'meals', '15.00'),\n ]\n cash_on_hand, report, replenishment = process_petty_cash(transactions)\n print('Cash on hand: {}'.format(cash_on_hand))\n print('Category report:')\n for category in sorted(report):\n print(' {}: {}'.format(category, report[category]))\n print('Replenishment needed: {}'.format(replenishment))\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2423, "topic": "petty cash logs and replenishment", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 780, "latency_s": 10.0}} +{"prompt": [{"role": "user", "content": "Write a function `aging_report(invoices)` that produces an accounts receivable aging report from a list of invoices. Each invoice is a tuple `(invoice_id, customer, amount, days_outstanding)`, where `amount` is a string representing a money value (use `Decimal` for exact arithmetic) and `days_outstanding` is a non-negative integer. Buckets are: 'Current' (0-30 days), '31-60', '61-90', 'Over 90'. Return a dict mapping bucket name to the total amount in that bucket (quantized to 2 decimal places with ROUND_HALF_UP), including all four buckets even if empty, plus a 'Total' key with the grand total. Example: invoices = [('INV-1', 'Acme', '150.00', 12), ('INV-2', 'Acme', '99.99', 45), ('INV-3', 'Beta', '250.00', 91)] gives {'Current': Decimal('150.00'), '31-60': Decimal('99.99'), '61-90': Decimal('0.00'), 'Over 90': Decimal('250.00'), 'Total': Decimal('499.99')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef aging_report(invoices):\n buckets = ['Current', '31-60', '61-90', 'Over 90']\n totals = {b: Decimal('0.00') for b in buckets}\n two = Decimal('0.01')\n for invoice_id, customer, amount, days in invoices:\n amt = Decimal(amount)\n if days <= 30:\n bucket = 'Current'\n elif days <= 60:\n bucket = '31-60'\n elif days <= 90:\n bucket = '61-90'\n else:\n bucket = 'Over 90'\n totals[bucket] += amt\n result = {}\n grand = Decimal('0.00')\n for b in buckets:\n q = totals[b].quantize(two, rounding=ROUND_HALF_UP)\n result[b] = q\n grand += q\n result['Total'] = grand.quantize(two, rounding=ROUND_HALF_UP)\n return result\n\n\nif __name__ == '__main__':\n invoices = [\n ('INV-1', 'Acme', '150.00', 12),\n ('INV-2', 'Acme', '99.99', 45),\n ('INV-3', 'Beta', '250.00', 91),\n ]\n print(aging_report(invoices))"}], "meta": {"idx": 2420, "topic": "accounts receivable and payable aging reports", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 482, "latency_s": 28.2}} +{"prompt": [{"role": "user", "content": "Write a function `account_balance(entries)` that computes the balance of a ledger account from a list of entries, where each entry is a tuple `(type, amount)` with `type` being either the string 'debit' or 'credit' and `amount` a string representing a monetary value. Use `decimal.Decimal` for all arithmetic so no floating-point errors occur; raise `ValueError` if the type is not 'debit'/'credit' or the amount cannot be parsed as a Decimal or is negative. The balance is the sum of debit amounts minus the sum of credit amounts, and the result must be a `Decimal` quantized to exactly 2 decimal places with ROUND_HALF_UP. For example, `account_balance([('debit', '100.10'), ('credit', '25.055'), ('debit', '0.005')])` returns `Decimal('75.06')`. Also include a `unittest.TestCase` class with at least four tests covering: the worked example, an empty ledger returning `Decimal('0.00')`, an invalid entry type raising `ValueError`, and a negative amount raising `ValueError`."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n\nTWO_PLACES = Decimal('0.01')\n\n\ndef account_balance(entries):\n balance = Decimal('0')\n for entry_type, amount_str in entries:\n if entry_type not in ('debit', 'credit'):\n raise ValueError(f\"Invalid entry type: {entry_type!r}\")\n try:\n amount = Decimal(amount_str)\n except (InvalidOperation, TypeError):\n raise ValueError(f\"Invalid amount: {amount_str!r}\")\n if amount < 0:\n raise ValueError(f\"Amount must be non-negative: {amount_str!r}\")\n if entry_type == 'debit':\n balance += amount\n else:\n balance -= amount\n return balance.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\n\nclass TestAccountBalance(unittest.TestCase):\n def test_worked_example(self):\n entries = [('debit', '100.10'), ('credit', '25.055'), ('debit', '0.005')]\n self.assertEqual(account_balance(entries), Decimal('75.06'))\n\n def test_empty_ledger(self):\n self.assertEqual(account_balance([]), Decimal('0.00'))\n\n def test_invalid_entry_type(self):\n with self.assertRaises(ValueError):\n account_balance([('payment', '10.00')])\n\n def test_negative_amount(self):\n with self.assertRaises(ValueError):\n account_balance([('debit', '-5.00')])\n\n def test_credit_only(self):\n self.assertEqual(\n account_balance([('credit', '10.00'), ('credit', '2.50')]),\n Decimal('-12.50'),\n )\n\n\nif __name__ == '__main__':\n unittest.main()"}], "meta": {"idx": 2427, "topic": "unit tests for accounting functions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 661, "latency_s": 7.7}} +{"prompt": [{"role": "user", "content": "A talent-and-services agency books daily transactions, and for each transaction it must split the gross amount into three ledger postings: a tiered sales commission, a tip pool divided among support staff, and a house share that absorbs all rounding residuals. The commission is computed in two brackets: the stated rate applies to the first 200.00 of gross, and exactly half the rate applies to the portion above 200.00, with each bracket rounded to cents using ROUND_HALF_UP before summing. The tip pool is tip_rate percent of gross, rounded to cents with ROUND_HALF_UP, then split among K staff using the largest-remainder method: each staff member's exact share is floored to cents, leftover cents are handed out one-by-one to the shares with the largest fractional remainder (ties broken by lower staff index), and if K is 0 the whole pool falls to the house. The house share is gross minus commission minus tips actually paid, so each transaction's ledger must balance exactly. Input is an integer T followed by T lines 'id gross commission_rate tip_rate staff_count' (rates are percentages, so 5 means 5%); output one line per transaction 'id commission=... tips=[...] house=...' plus a final line 'TOTAL gross=... commission=... tips=... house=... BALANCED' (or IMBALANCED if any transaction fails to sum to its gross). Worked example: 'T101 333.33 5 3 3' gives commission 200.00\u00d75% = 10.00 plus 133.33\u00d72.5% = 3.33, total 13.33; tip pool 333.33\u00d73% = 9.9999 \u2192 10.00, split among 3 staff as base 3.33 each with the one leftover cent going to staff 0 on the tie, i.e. 3.34, 3.33, 3.33; house = 333.33 \u2212 13.33 \u2212 10.00 = 310.00, so the output line is 'T101 commission=13.33 tips=[3.34,3.33,3.33] house=310.00'."}], "completion": [{"role": "assistant", "content": "import sys\nfrom decimal import Decimal, ROUND_HALF_UP, ROUND_DOWN\n\nCENT = Decimal(\"0.01\")\nBRACKET = Decimal(\"200.00\")\nHUNDRED = Decimal(100)\nTWO = Decimal(2)\n\n\ndef q2(value, rounding=ROUND_HALF_UP):\n return value.quantize(CENT, rounding=rounding)\n\n\ndef compute_commission(gross, rate_pct):\n rate = rate_pct / HUNDRED\n if gross <= BRACKET:\n return q2(gross * rate)\n first = q2(BRACKET * rate)\n rest = q2((gross - BRACKET) * rate / TWO)\n return first + rest\n\n\ndef split_tip_pool(pool, k):\n if k <= 0:\n return []\n if k == 1:\n return [pool]\n exact = pool / k\n base = q2(exact, ROUND_DOWN)\n cents_left = int((pool - base * k) / CENT)\n shares = [base] * k\n order = sorted(range(k), key=lambda i: (-(exact - base), i))\n for j in range(cents_left):\n shares[order[j]] += CENT\n return shares\n\n\ndef fmt(d):\n return str(d.quantize(CENT))\n\n\ndef main():\n tokens = sys.stdin.read().split()\n if not tokens:\n return\n idx = 0\n t = int(tokens[idx])\n idx += 1\n\n total_gross = Decimal(0)\n total_comm = Decimal(0)\n total_tips = Decimal(0)\n total_house = Decimal(0)\n balanced = True\n lines = []\n\n for _ in range(t):\n tid = tokens[idx]\n gross = Decimal(tokens[idx + 1])\n rate_pct = Decimal(tokens[idx + 2])\n tip_pct = Decimal(tokens[idx + 3])\n k = int(tokens[idx + 4])\n idx += 5\n\n comm = compute_commission(gross, rate_pct)\n pool = q2(gross * tip_pct / HUNDRED)\n shares = split_tip_pool(pool, k)\n tips_paid = sum(shares, Decimal(0))\n house = gross - comm - tips_paid\n\n if comm + tips_paid + house != gross:\n balanced = False\n\n tip_str = \"[\" + \",\".join(fmt(s) for s in shares) + \"]\"\n lines.append(\n \"{} commission={} tips={} house={}\".format(\n tid, fmt(comm), tip_str, fmt(house)\n )\n )\n\n total_gross += gross\n total_comm += comm\n total_tips += tips_paid\n total_house += house\n\n grand_ok = total_comm + total_tips + total_house == total_gross\n status = \"BALANCED\" if balanced and grand_ok else \"IMBALANCED\"\n lines.append(\n \"TOTAL gross={} commission={} tips={} house={} {}\".format(\n fmt(total_gross), fmt(total_comm), fmt(total_tips),\n fmt(total_house), status\n )\n )\n print(\"\\n\".join(lines))\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2417, "topic": "commission, tip, and percentage splits", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1082, "latency_s": 45.0}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts as a list of tuples (account_code, account_name, account_type) where account_type is one of 'asset', 'liability', 'equity', 'revenue', 'expense'. You are also given a list of expense transactions, each a tuple (account_code, description, amount_str), where amount_str is a decimal string representing a positive expense amount. Write a function categorize_expenses(accounts, transactions) that returns a dictionary mapping each expense account's name to the total amount spent in it, using Decimal arithmetic rounded to 2 decimal places with ROUND_HALF_UP. Only transactions posted to accounts of type 'expense' should be included; transactions referencing unknown account codes or non-expense accounts must be ignored. Additionally, the function should include the key '_total' holding the sum of all included expense amounts (0.00 if none). For example, accounts = [('5000', 'Office Supplies', 'expense'), ('1000', 'Cash', 'asset')], transactions = [('5000', 'paper', '10.555'), ('1000', 'withdrawal', '500.00'), ('9999', 'mystery', '1.00'), ('5000', 'pens', '2.50')] returns {'Office Supplies': Decimal('13.06'), '_total': Decimal('13.06')} because 10.555 rounds to 10.56 (ROUND_HALF_UP) and the asset/unknown transactions are ignored."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef categorize_expenses(accounts, transactions):\n expense_names = {}\n for code, name, acc_type in accounts:\n if acc_type == 'expense':\n expense_names[code] = name\n\n totals = {}\n grand_total = Decimal('0')\n for code, description, amount_str in transactions:\n if code not in expense_names:\n continue\n amount = Decimal(amount_str)\n name = expense_names[code]\n totals[name] = totals.get(name, Decimal('0')) + amount\n grand_total += amount\n\n result = {}\n for name, total in totals.items():\n result[name] = total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n result['_total'] = grand_total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n return result\n\n\nif __name__ == '__main__':\n accounts = [('5000', 'Office Supplies', 'expense'), ('1000', 'Cash', 'asset')]\n transactions = [\n ('5000', 'paper', '10.555'),\n ('1000', 'withdrawal', '500.00'),\n ('9999', 'mystery', '1.00'),\n ('5000', 'pens', '2.50'),\n ]\n print(categorize_expenses(accounts, transactions))"}], "meta": {"idx": 2418, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "novita", "in_tokens": 199, "out_tokens": 643, "latency_s": 7.8}} +{"prompt": [{"role": "user", "content": "Write a function `next_monthly_rent_postings(start_year, start_month, amount, months)` that simulates a recurring monthly rent posting for a small ledger. Each month, a rent amount (given as a string like '850.00') is posted to a ledger balance that starts at Decimal('0.00'). The function returns a list of (year, month, balance) tuples, where balance is the running ledger balance (as a Decimal rounded to 2 places) after each monthly posting. The postings start in the given year/month and continue for the specified number of months, rolling over years correctly (e.g., after month 12 comes January of the next year). For example, next_monthly_rent_postings(2023, 11, '850.00', 3) must return [(2023, 11, Decimal('850.00')), (2023, 12, Decimal('1700.00')), (2024, 1, Decimal('2550.00'))]. Use Decimal arithmetic so no floating point errors occur."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom typing import List, Tuple\n\ndef next_monthly_rent_postings(start_year: int, start_month: int, amount: str, months: int) -> List[Tuple[int, int, Decimal]]:\n rent = Decimal(amount)\n balance = Decimal('0.00')\n results = []\n year, month = start_year, start_month\n for _ in range(months):\n balance += rent\n results.append((year, month, balance.quantize(Decimal('0.01'))))\n month += 1\n if month > 12:\n month = 1\n year += 1\n return results\n\nif __name__ == '__main__':\n print(next_monthly_rent_postings(2023, 11, '850.00', 3))"}], "meta": {"idx": 2425, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 380, "latency_s": 24.8}} +{"prompt": [{"role": "user", "content": "You are given a list of ledger entries from a company's cash account, where each entry is a tuple (date, description, amount). Positive amounts are deposits and negative amounts are withdrawals, all given as strings representing decimal currency values. Write a function `reconcile(entries)` that returns the running balance of the account as a Decimal, rounded to 2 decimal places with ROUND_HALF_UP. Use the Decimal type for all arithmetic to avoid floating point errors. For example, given entries = [('2024-01-01', 'Opening deposit', '1000.00'), ('2024-01-05', 'Office supplies', '-45.50'), ('2024-01-10', 'Client payment', '312.675')], the function should return Decimal('1267.18') because 1000.00 - 45.50 + 312.675 = 1267.175, which rounds to 1267.18. If the list is empty, return Decimal('0.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef reconcile(entries):\n balance = Decimal('0')\n for date, description, amount in entries:\n balance += Decimal(amount)\n return balance.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-01', 'Opening deposit', '1000.00'),\n ('2024-01-05', 'Office supplies', '-45.50'),\n ('2024-01-10', 'Client payment', '312.675'),\n ]\n print(reconcile(entries)) # 1267.18\n print(reconcile([])) # 0.00"}], "meta": {"idx": 2430, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 346, "latency_s": 8.1}} +{"prompt": [{"role": "user", "content": "You are given a list of double-entry ledger entries for a small business, where each entry is a tuple (account, debit, credit) with amounts as strings representing dollars and cents. Accounts follow the convention: accounts starting with '1' or '5' are debit-normal (assets, expenses), and accounts starting with '2', '3', or '4' are credit-normal (liabilities, equity, revenue). Write a function summarize(entries) that returns a tuple (net_income, total_assets, total_liabilities_and_equity). Net income equals total revenue (accounts starting with '4') minus total expenses (accounts starting with '5'), where revenue and expense balances are computed as the sum of debits minus credits for debit-normal accounts (expenses) and credits minus debits for credit-normal accounts (revenue). Total assets is the sum of debit balances for accounts starting with '1'; total liabilities is the sum of credit balances for accounts starting with '2'; and equity (accounts starting with '3') is the sum of its credit balances plus net income. All arithmetic must use Decimal with ROUND_HALF_UP rounding to cents at each reported figure. For example, entries = [('1010 Cash', '12500.00', '0.00'), ('4010 Sales', '0.00', '12500.00'), ('5010 Rent', '1000.255', '0.00'), ('1010 Cash', '0.00', '1000.255'), ('3010 Capital', '0.00', '0.00')] should give net income = 12500.00 - 1000.26 = 11499.74, total assets = 11499.74, and total liabilities and equity = 0 + 3010's balance 0 + net income 11499.74 = 11499.74, so the function returns (Decimal('11499.74'), Decimal('11499.74'), Decimal('11499.74'))."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _round(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef summarize(entries):\n debits = {}\n credits = {}\n for account, debit, credit in entries:\n d = Decimal(debit)\n c = Decimal(credit)\n debits[account] = debits.get(account, Decimal('0')) + d\n credits[account] = credits.get(account, Decimal('0')) + c\n\n revenue = Decimal('0')\n expenses = Decimal('0')\n assets = Decimal('0')\n liabilities = Decimal('0')\n equity_ex_ni = Decimal('0')\n\n for account in set(debits) | set(credits):\n d = debits.get(account, Decimal('0'))\n c = credits.get(account, Decimal('0'))\n prefix = account[0] if account else ''\n if prefix == '1':\n assets += d - c\n elif prefix == '2':\n liabilities += c - d\n elif prefix == '3':\n equity_ex_ni += c - d\n elif prefix == '4':\n revenue += c - d\n elif prefix == '5':\n expenses += d - c\n\n net_income = _round(revenue - expenses)\n total_assets = _round(assets)\n total_le = _round(liabilities + equity_ex_ni + net_income)\n return (net_income, total_assets, total_le)\n\n\nif __name__ == '__main__':\n entries = [\n ('1010 Cash', '12500.00', '0.00'),\n ('4010 Sales', '0.00', '12500.00'),\n ('5010 Rent', '1000.255', '0.00'),\n ('1010 Cash', '0.00', '1000.255'),\n ('3010 Capital', '0.00', '0.00'),\n ]\n assert summarize(entries) == (Decimal('11499.74'), Decimal('11499.74'), Decimal('11499.74'))\n print(summarize(entries))"}], "meta": {"idx": 2431, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 826, "latency_s": 8.0}} +{"prompt": [{"role": "user", "content": "You are reconciling a bank statement against a company ledger. Given a list of ledger entries (each a tuple of description, debit, credit) and a list of bank statement entries (same format), identify entries that appear in the ledger but are missing from the bank statement, and compute the reconciled balance difference. All monetary amounts are strings representing dollars and cents (e.g. '125.50'). Use Decimal arithmetic with ROUND_HALF_UP rounding to cents. Write a function reconcile(ledger, bank) that returns a dict with keys 'missing_from_bank' (a sorted list of descriptions of ledger entries not found in the bank statement) and 'difference' (the total debits minus total credits of those missing entries, as a Decimal quantized to 2 places). An entry matches if both its description and amounts are equal. Example: ledger = [('Rent', '1200.00', '0.00'), ('Office supplies', '85.50', '0.00'), ('Client payment', '0.00', '2500.00')], bank = [('Rent', '1200.00', '0.00'), ('Client payment', '0.00', '2500.00')] should return {'missing_from_bank': ['Office supplies'], 'difference': Decimal('85.50')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import Counter\n\n\ndef _norm(entry):\n desc, debit, credit = entry\n return (desc, Decimal(debit).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP),\n Decimal(credit).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))\n\n\ndef reconcile(ledger, bank):\n bank_counts = Counter(_norm(e) for e in bank)\n missing = []\n for entry in ledger:\n key = _norm(entry)\n if bank_counts[key] > 0:\n bank_counts[key] -= 1\n else:\n missing.append(key)\n total = sum((d - c) for _, d, c in missing) if missing else Decimal('0.00')\n return {\n 'missing_from_bank': sorted(desc for desc, _, _ in missing),\n 'difference': total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP),\n }\n\n\nif __name__ == '__main__':\n ledger = [('Rent', '1200.00', '0.00'),\n ('Office supplies', '85.50', '0.00'),\n ('Client payment', '0.00', '2500.00')]\n bank = [('Rent', '1200.00', '0.00'),\n ('Client payment', '0.00', '2500.00')]\n result = reconcile(ledger, bank)\n assert result == {'missing_from_bank': ['Office supplies'],\n 'difference': Decimal('85.50')}\n print(result)"}], "meta": {"idx": 2432, "topic": "bank statement reconciliation", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 604, "latency_s": 5.4}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, useful_life, rate=None)` that produces a straight-line depreciation schedule, or a declining-balance schedule if a `rate` (e.g. 0.4 for 40%) is given. All money values must be handled with `decimal.Decimal`, rounded to 2 places with `ROUND_HALF_UP`. For straight-line, each year's depreciation is (cost - salvage) / useful_life, with the final year adjusted so the book value ends exactly at salvage. For declining balance, each year's depreciation is the prior book value times `rate`, but depreciation is capped so book value never drops below salvage; once book value reaches salvage, remaining years have zero depreciation. Return a list of tuples (year, depreciation, accumulated_depreciation, ending_book_value) for years 1..useful_life. Example: cost=10000, salvage=1000, useful_life=4, rate=0.4 should give year 1 depreciation 4000.00, accumulated 4000.00, ending book value 6000.00; year 4 depreciation 216.00, ending book value 1000.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef depreciation_schedule(cost, salvage, useful_life, rate=None):\n cost = Decimal(str(cost))\n salvage = Decimal(str(salvage))\n two = Decimal('0.01')\n\n def q(x):\n return x.quantize(two, rounding=ROUND_HALF_UP)\n\n schedule = []\n book = q(cost)\n accum = Decimal('0.00')\n\n for year in range(1, useful_life + 1):\n if rate is None:\n dep = q((cost - salvage) / Decimal(useful_life))\n if year == useful_life:\n dep = q(cost - salvage - accum)\n else:\n dep = q(book * Decimal(str(rate)))\n if book - dep < salvage:\n dep = q(book - salvage)\n if dep < 0:\n dep = Decimal('0.00')\n book = q(book - dep)\n accum = q(accum + dep)\n schedule.append((year, dep, accum, book))\n\n return schedule\n\n\nif __name__ == '__main__':\n for row in depreciation_schedule(10000, 1000, 4, rate=0.4):\n print(row)\n for row in depreciation_schedule(10000, 1000, 4):\n print(row)"}], "meta": {"idx": 2428, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 536, "latency_s": 38.2}} +{"prompt": [{"role": "user", "content": "Write a function `reconcile(book_entries, bank_entries, tolerance_days=1)` that reconciles a company's book (internal) cash ledger against the bank statement. Each entry is a tuple `(date, description, amount)` where `date` is a `datetime.date`, `description` is a string, and `amount` is money as a string or Decimal where positive values increase the balance; all amounts must be handled with `Decimal` and rounded to cents using `ROUND_HALF_UP`. A book entry matches a bank entry only if the cent-rounded amounts are identical, the dates differ by at most `tolerance_days`, and each bank entry is matched at most once; when several bank entries qualify, prefer the one with the smallest date difference, breaking ties by the earliest date, then by original statement order. Bank-only entries (e.g. service fees, interest) are adjustments to record in the books, and book-only entries (e.g. deposits in transit, outstanding checks) are timing differences on the bank side, so the adjusted book balance equals the raw book balance plus all bank-only amounts, and the adjusted bank balance equals the raw bank balance plus all book-only amounts; the statement reconciles only if the two adjusted balances are exactly equal to the cent. The function must return a dict with keys `book_balance`, `bank_balance`, `adjusted_book_balance`, `adjusted_bank_balance`, `matched` (list of `(book_index, bank_index)` pairs), `bank_only`, `book_only`, `reconciled` (bool), and `report` (a human-readable multi-line reconciliation report). Worked example: book entries are 2024-06-28 deposit +500.00, 2024-06-29 check -320.50, 2024-06-30 transfer -125.00 (book balance 54.50); bank entries are 2024-06-28 deposit +500.00, 2024-06-30 check -320.50 (clears within the 1-day tolerance even though the book date is 06-29), 2024-06-29 interest +3.25, 2024-06-30 service fee -12.40 (bank balance 170.35). The transfer is book-only, so the adjusted bank balance is 170.35 - 125.00 = 45.35, and the fee and interest are bank-only, so the adjusted book balance is 54.50 + 3.25 - 12.40 = 45.35; the result must report `reconciled == True` with both adjusted balances equal to Decimal('45.35')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nCENT = Decimal(\"0.01\")\n\n\ndef to_cents(value):\n \"\"\"Convert any numeric input to a Decimal rounded to cents (ROUND_HALF_UP).\"\"\"\n d = value if isinstance(value, Decimal) else Decimal(str(value))\n return d.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _fmt(amount):\n \"\"\"Format a cent-rounded Decimal with an explicit sign for report lines.\"\"\"\n sign = \"+\" if amount > 0 else \"\" if amount < 0 else \" \"\n return \"{}{}\".format(sign, amount)\n\n\ndef reconcile(book_entries, bank_entries, tolerance_days=1):\n \"\"\"Reconcile a book cash ledger against a bank statement.\n\n Returns a dict with raw and adjusted balances, matched pairs,\n unmatched items on each side, a reconciled flag, and a text report.\n \"\"\"\n book = [(d, desc, to_cents(amt)) for d, desc, amt in book_entries]\n bank = [(d, desc, to_cents(amt)) for d, desc, amt in bank_entries]\n\n zero = Decimal(\"0\")\n book_balance = to_cents(sum((e[2] for e in book), zero))\n bank_balance = to_cents(sum((e[2] for e in bank), zero))\n\n # One-to-one matching: walk book entries chronologically; for each,\n # pick the unused bank entry with the same amount whose date is within\n # tolerance, preferring the smallest date gap, then earliest date,\n # then original statement order.\n used_bank = [False] * len(bank)\n matched = []\n book_order = sorted(range(len(book)), key=lambda i: (book[i][0], book[i][1], i))\n for bi in book_order:\n bdate, _bdesc, bamt = book[bi]\n best_key = None\n best_j = None\n for j in range(len(bank)):\n if used_bank[j]:\n continue\n gdate, _gdesc, gamt = bank[j]\n if gamt != bamt:\n continue\n diff = abs((gdate - bdate).days)\n if diff > tolerance_days:\n continue\n key = (diff, gdate, j)\n if best_key is None or key < best_key:\n best_key = key\n best_j = j\n if best_j is not None:\n used_bank[best_j] = True\n matched.append((bi, best_j))\n\n matched_book_idx = {bi for bi, _ in matched}\n bank_only = [bank[j] for j in range(len(bank)) if not used_bank[j]]\n book_only = [\n book[i]\n for i in sorted(\n (i for i in range(len(book)) if i not in matched_book_idx),\n key=lambda i: (book[i][0], book[i][1], i),\n )\n ]\n\n # Bank-only items must be recorded in the books (fees, interest, errors).\n # Book-only items are timing differences (deposits in transit, outstanding checks).\n adjusted_book = to_cents(book_balance + sum((e[2] for e in bank_only), zero))\n adjusted_bank = to_cents(bank_balance + sum((e[2] for e in book_only), zero))\n reconciled = adjusted_book == adjusted_bank\n\n lines = [\"BANK RECONCILIATION\"]\n lines.append(\"Book balance: {}\".format(book_balance))\n lines.append(\"Bank statement balance: {}\".format(bank_balance))\n lines.append(\"Bank-only items (record in books):\")\n if bank_only:\n for d, desc, amt in bank_only:\n lines.append(\" {} {:<28} {}\".format(d.isoformat(), desc, _fmt(amt)))\n else:\n lines.append(\" (none)\")\n lines.append(\"Adjusted book balance: {}\".format(adjusted_book))\n lines.append(\"Book-only items (in transit / outstanding):\")\n if book_only:\n for d, desc, amt in book_only:\n lines.append(\" {} {:<28} {}\".format(d.isoformat(), desc, _fmt(amt)))\n else:\n lines.append(\" (none)\")\n lines.append(\"Adjusted bank balance: {}\".format(adjusted_bank))\n lines.append(\"Status: {}\".format(\"RECONCILED\" if reconciled else \"OUT OF BALANCE\"))\n report = \"\\n\".join(lines)\n\n return {\n \"book_balance\": book_balance,\n \"bank_balance\": bank_balance,\n \"adjusted_book_balance\": adjusted_book,\n \"adjusted_bank_balance\": adjusted_bank,\n \"matched\": matched,\n \"bank_only\": bank_only,\n \"book_only\": book_only,\n \"reconciled\": reconciled,\n \"report\": report,\n }\n\n\nif __name__ == \"__main__\":\n book_entries = [\n (date(2024, 6, 28), \"DEPOSIT\", \"500.00\"),\n (date(2024, 6, 29), \"CHECK #1042\", \"-320.50\"),\n (date(2024, 6, 30), \"TRANSFER TO SAVINGS\", \"-125.00\"),\n ]\n bank_entries = [\n (date(2024, 6, 28), \"DEPOSIT\", \"500.00\"),\n (date(2024, 6, 30), \"CHECK #1042\", \"-320.50\"),\n (date(2024, 6, 29), \"INTEREST EARNED\", \"3.25\"),\n (date(2024, 6, 30), \"SERVICE FEE\", \"-12.40\"),\n ]\n\n result = reconcile(book_entries, bank_entries, tolerance_days=1)\n print(result[\"report\"])\n\n assert result[\"book_balance\"] == Decimal(\"54.50\")\n assert result[\"bank_balance\"] == Decimal(\"170.35\")\n assert result[\"adjusted_book_balance\"] == Decimal(\"45.35\")\n assert result[\"adjusted_bank_balance\"] == Decimal(\"45.35\")\n assert result[\"reconciled\"] is True\n assert len(result[\"matched\"]) == 2\n assert sorted(e[1] for e in result[\"bank_only\"]) == [\n (date(2024, 6, 29), \"INTEREST EARNED\", Decimal(\"3.25\")),\n (date(2024, 6, 30), \"SERVICE FEE\", Decimal(\"-12.40\")),\n ]\n assert result[\"book_only\"] == [\n (date(2024, 6, 30), \"TRANSFER TO SAVINGS\", Decimal(\"-125.00\"))\n ]\n print(\"\\nAll assertions passed.\")"}], "meta": {"idx": 2414, "topic": "bank statement reconciliation", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1963, "latency_s": 95.1}} +{"prompt": [{"role": "user", "content": "Write a program that produces a depreciation schedule for a fixed asset using both straight-line and double-declining-balance methods. The input consists of: the asset name (string), the purchase cost (Decimal), the salvage value (Decimal), and the useful life in whole years (int). Using Decimal arithmetic with ROUND_HALF_UP rounding to cents, produce a report (list of tuples per year: year, straight-line depreciation expense, straight-line accumulated depreciation, straight-line book value, DDB depreciation expense, DDB accumulated depreciation, DDB book value). Straight-line depreciation is (cost - salvage) / life each year. Double-declining-balance uses a rate of 2/life applied to the beginning book value, but depreciation must be capped so the book value never drops below salvage (reduce the final depreciation amount if needed, possibly to zero). Print the schedule with each amount formatted to 2 decimal places. For example, for asset 'Delivery Van', cost 25000.00, salvage 5000.00, life 5: straight-line expense is 4000.00 each year; DDB expenses are 10000.00, 6000.00, 3600.00, 400.00, 0.00 (capped at salvage), and both methods end with book value 5000.00. The program should read input values defined in code (no console input needed) and print a formatted table for this example."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef q(value):\n \"\"\"Round a Decimal to cents, half-up.\"\"\"\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef straight_line_schedule(cost, salvage, life):\n rows = []\n annual = q((cost - salvage) / Decimal(life))\n accumulated = Decimal('0.00')\n book = cost\n for year in range(1, life + 1):\n expense = annual\n if year == life:\n # Final year adjusts for any rounding drift so book value hits salvage exactly.\n expense = q(book - salvage)\n accumulated = q(accumulated + expense)\n book = q(book - expense)\n rows.append((year, expense, accumulated, book))\n return rows\n\n\ndef ddb_schedule(cost, salvage, life):\n rows = []\n rate = Decimal(2) / Decimal(life)\n accumulated = Decimal('0.00')\n book = cost\n for year in range(1, life + 1):\n raw = q(book * rate)\n # Cap so book value never falls below salvage.\n expense = min(raw, q(book - salvage))\n if expense < Decimal('0.00'):\n expense = Decimal('0.00')\n accumulated = q(accumulated + expense)\n book = q(book - expense)\n rows.append((year, expense, accumulated, book))\n return rows\n\n\ndef print_schedule(asset, cost, salvage, life):\n sl = straight_line_schedule(cost, salvage, life)\n ddb = ddb_schedule(cost, salvage, life)\n print(f\"Depreciation Schedule for {asset}\")\n print(f\"Cost: {q(cost):>12} Salvage: {q(salvage):>12} Life: {life} years\")\n print()\n header = (\"Year\", \"SL Expense\", \"SL Accum\", \"SL Book\",\n \"DDB Expense\", \"DDB Accum\", \"DDB Book\")\n print(\"{:>4} {:>12} {:>12} {:>12} {:>12} {:>12} {:>12}\".format(*header))\n for sl_row, ddb_row in zip(sl, ddb):\n year = sl_row[0]\n values = (year,\n f\"{sl_row[1]:.2f}\", f\"{sl_row[2]:.2f}\", f\"{sl_row[3]:.2f}\",\n f\"{ddb_row[1]:.2f}\", f\"{ddb_row[2]:.2f}\", f\"{ddb_row[3]:.2f}\")\n print(\"{:>4} {:>12} {:>12} {:>12} {:>12} {:>12} {:>12}\".format(*values))\n\n\ndef main():\n asset = 'Delivery Van'\n cost = Decimal('25000.00')\n salvage = Decimal('5000.00')\n life = 5\n print_schedule(asset, cost, salvage, life)\n\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2435, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 930, "latency_s": 21.0}} +{"prompt": [{"role": "user", "content": "Implement an inventory cost layer tracker that supports three valuation methods: FIFO, LIFO, and weighted average. Read a transaction log where each line is one of: 'BUY ', 'SELL ', or 'REPORT ' (method is one of FIFO, LIFO, WAVG). For BUY, add a cost layer (qty, unit_cost) with money handled as Decimal with 2-decimal rounding. For SELL, remove cost from the layers according to the method (FIFO consumes oldest layers first, LIFO consumes newest layers first, WAVG replaces all layers with a single layer at the weighted-average cost of remaining units before consuming) and record a realized profit/loss = sale revenue - cost of goods sold, where revenue = qty * unit_price and COGS is computed with the same method, all rounded to 2 decimals using ROUND_HALF_UP. For REPORT, print the remaining inventory value under the given method (FIFO/LIFO value the layers as stored; WAVG computes total cost / total qty across layers) followed by the cumulative realized P/L, formatted as 'INVENTORY= P/L=' with 2 decimals. Assume sells never exceed available quantity. Example: given the log ['BUY 10 5.00', 'BUY 10 8.00', 'SELL 5 10.00', 'REPORT FIFO', 'REPORT LIFO', 'REPORT WAVG'], the output is 'INVENTORY=110.00 P/L=25.00' (FIFO: COGS=25.00, remaining 5@5.00 + 10@8.00), 'INVENTORY=110.00 P/L=10.00' (LIFO: COGS=40.00, remaining 10@5.00 + 5@8.00), 'INVENTORY=110.00 P/L=16.25' (WAVG: avg cost 6.50, COGS=32.50, remaining 15 units valued at 97.50... but note WAVG treats the sale as consuming from a merged 6.50 layer, so inventory = 15*6.50 = 97.50; use the values shown: FIFO line is 'INVENTORY=110.00 P/L=25.00', LIFO line is 'INVENTORY=110.00 P/L=10.00', WAVG line is 'INVENTORY=97.50 P/L=16.25')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef money(x):\n return Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef process_log(lines):\n fifo_layers = [] # list of [qty, cost] oldest first\n lifo_layers = [] # same list, consumed from the end\n wavg_layers = []\n pl = {'FIFO': Decimal('0'), 'LIFO': Decimal('0'), 'WAVG': Decimal('0')}\n out = []\n\n for line in lines:\n parts = line.split()\n cmd = parts[0]\n if cmd == 'BUY':\n qty = int(parts[1])\n cost = money(parts[2])\n for layers in (fifo_layers, lifo_layers, wavg_layers):\n layers.append([qty, cost])\n elif cmd == 'SELL':\n qty = int(parts[1])\n price = money(parts[2])\n revenue = money(Decimal(qty) * price)\n for method, layers in (('FIFO', fifo_layers), ('LIFO', lifo_layers), ('WAVG', wavg_layers)):\n if method == 'WAVG':\n total_qty = sum(q for q, _ in layers)\n total_cost = sum(q * c for q, c in layers)\n if total_qty > 0:\n avg = money(total_cost / total_qty)\n layers[:] = [[total_qty, avg]]\n remaining = qty\n cogs = Decimal('0')\n while remaining > 0:\n if method == 'LIFO':\n layer = layers[-1]\n else:\n layer = layers[0]\n take = min(remaining, layer[0])\n cogs += Decimal(take) * layer[1]\n layer[0] -= take\n remaining -= take\n if layer[0] == 0:\n if method == 'LIFO':\n layers.pop()\n else:\n layers.pop(0)\n cogs = money(cogs)\n pl[method] = money(pl[method] + revenue - cogs)\n elif cmd == 'REPORT':\n method = parts[1]\n layers = {'FIFO': fifo_layers, 'LIFO': lifo_layers, 'WAVG': wavg_layers}[method]\n inv = money(sum(Decimal(q) * c for q, c in layers))\n out.append('INVENTORY={} P/L={}'.format(inv, pl[method]))\n return out\n\n\nif __name__ == '__main__':\n log = ['BUY 10 5.00', 'BUY 10 8.00', 'SELL 5 10.00', 'REPORT FIFO', 'REPORT LIFO', 'REPORT WAVG']\n for line in process_log(log):\n print(line)"}], "meta": {"idx": 2436, "topic": "inventory valuation (FIFO, LIFO, weighted average)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1073, "latency_s": 48.0}} +{"prompt": [{"role": "user", "content": "Implement a miniature general-ledger engine. You receive journal entries, each with a memo and a list of lines (account, side, amount) where side is 'D' or 'C' and amount is a decimal string; every amount must first be quantized to cents with ROUND_HALF_EVEN. An entry posts to the ledger only if its total debits equal its total credits exactly after quantization; otherwise it is quarantined together with its out-of-balance difference. Balanced entries must be posted chronologically into per-account T-accounts that track total debits, total credits, and the individual postings in order. You must then produce a trial balance in debit-positive convention (balance = debit_total - credit_total per account, sorted by account name) and verify that total debit balances equal total credit balances, and finally flag abnormal balances: accounts whose net balance lies on the opposite side of their declared normal side. Worked example: entries [('Invoice 101', [(Cash,D,1000.00), (Services Revenue,C,1000.00)]), ('Rent', [(Rent Expense,D,250.005), (Cash,C,250.00)]), ('Supplies', [(Supplies,D,50.00), (Cash,C,49.99)]), ('Refund', [(Services Revenue,D,1200.00), (Cash,C,1200.00)])] with normal sides Cash=D, Services Revenue=C, Rent Expense=D: since 250.005 rounds to 250.00 under ROUND_HALF_EVEN the rent entry posts, the supplies entry is quarantined with difference 0.01, the trial balance shows Cash -450.00, Rent Expense 250.00, Services Revenue 200.00 with matching debit and credit totals of 450.00, and both Cash (credit balance despite normal debit side) and Services Revenue (debit balance despite normal credit side) are reported as abnormal."}], "completion": [{"role": "assistant", "content": "from dataclasses import dataclass, field\nfrom decimal import Decimal, ROUND_HALF_EVEN\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\ndef to_cents(raw):\n \"\"\"Quantize a decimal string/number to cents using banker's rounding.\"\"\"\n return Decimal(str(raw)).quantize(CENT, rounding=ROUND_HALF_EVEN)\n\n\n@dataclass\nclass TAccount:\n \"\"\"A T-account: debit side, credit side, and chronological postings.\"\"\"\n name: str\n debit_total: Decimal = ZERO\n credit_total: Decimal = ZERO\n postings: list = field(default_factory=list)\n\n def balance(self):\n \"\"\"Net balance in debit-positive convention.\"\"\"\n return (self.debit_total - self.credit_total).quantize(\n CENT, rounding=ROUND_HALF_EVEN\n )\n\n\ndef post_entries(entries, normal_sides):\n \"\"\"Post journal entries to T-accounts; quarantine unbalanced ones.\n\n Returns (ledger, quarantined) where ledger maps account name -> TAccount\n and quarantined is a list of dicts describing rejected entries.\n \"\"\"\n ledger = {}\n quarantined = []\n for idx, entry in enumerate(entries):\n memo = entry.get(\"memo\", \"\")\n lines = entry.get(\"lines\", [])\n\n # Validate sides and amounts, quantizing to cents.\n prepared = []\n valid = True\n for account, side, amount in lines:\n if side not in (\"D\", \"C\"):\n valid = False\n break\n try:\n amt = to_cents(amount)\n except Exception:\n valid = False\n break\n if amt < 0:\n valid = False\n break\n prepared.append((account, side, amt))\n\n if not valid or not prepared:\n quarantined.append({\n \"index\": idx,\n \"memo\": memo,\n \"difference\": None,\n \"reason\": \"invalid line (bad side, negative or unparsable amount)\",\n })\n continue\n\n total_debits = sum((a for _, s, a in prepared if s == \"D\"), ZERO)\n total_credits = sum((a for _, s, a in prepared if s == \"C\"), ZERO)\n difference = (total_debits - total_credits).quantize(\n CENT, rounding=ROUND_HALF_EVEN\n )\n\n if difference != ZERO:\n quarantined.append({\n \"index\": idx,\n \"memo\": memo,\n \"difference\": difference,\n \"reason\": \"unbalanced entry\",\n })\n continue\n\n # Post chronologically.\n for account, side, amt in prepared:\n acct = ledger.setdefault(account, TAccount(account))\n if side == \"D\":\n acct.debit_total += amt\n else:\n acct.credit_total += amt\n acct.postings.append({\n \"entry\": idx,\n \"side\": side,\n \"amount\": amt,\n \"memo\": memo,\n })\n\n return ledger, quarantined\n\n\ndef trial_balance(ledger):\n \"\"\"Return (balances, total_debits, total_credits, is_balanced).\n\n balances maps account name -> net balance (debit positive), sorted by name.\n \"\"\"\n balances = {name: acct.balance() for name, acct in sorted(ledger.items())}\n total_debits = sum((b for b in balances.values() if b > 0), ZERO)\n total_credits = sum((-b for b in balances.values() if b < 0), ZERO)\n is_balanced = (total_debits == total_credits)\n return balances, total_debits, total_credits, is_balanced\n\n\ndef abnormal_balances(ledger, normal_sides):\n \"\"\"Flag accounts whose net balance is on the wrong side of normal.\"\"\"\n out = []\n for name, acct in sorted(ledger.items()):\n normal = normal_sides.get(name)\n if normal is None:\n continue\n bal = acct.balance()\n if bal == ZERO:\n continue\n if (normal == \"D\" and bal < 0) or (normal == \"C\" and bal > 0):\n out.append({\n \"account\": name,\n \"balance\": bal,\n \"normal_side\": normal,\n })\n return out\n\n\ndef render_t_account(acct):\n \"\"\"Render a T-account as left (Dr) / right (Cr) columns.\"\"\"\n left = [(p[\"memo\"], p[\"amount\"]) for p in acct.postings if p[\"side\"] == \"D\"]\n right = [(p[\"memo\"], p[\"amount\"]) for p in acct.postings if p[\"side\"] == \"C\"]\n lines = [f\"Account: {acct.name}\"]\n lines.append(f\" {'DR':<28} | {'CR':<28}\")\n for i in range(max(len(left), len(right))):\n l = f\"{left[i][0]} {left[i][1]:>10}\" if i < len(left) else \" \" * 18\n r = f\"{right[i][0]} {right[i][1]:>10}\" if i < len(right) else \"\"\n lines.append(f\" {l:<28} | {r:<28}\")\n lines.append(\n f\" Totals: Dr {acct.debit_total} | Cr {acct.credit_total} \"\n f\"| Balance: {acct.balance()}\"\n )\n return \"\\n\".join(lines)\n\n\nif __name__ == \"__main__\":\n entries = [\n {\"memo\": \"Invoice 101\", \"lines\": [\n (\"Cash\", \"D\", \"1000.00\"),\n (\"Services Revenue\", \"C\", \"1000.00\"),\n ]},\n {\"memo\": \"Rent\", \"lines\": [\n (\"Rent Expense\", \"D\", \"250.005\"),\n (\"Cash\", \"C\", \"250.00\"),\n ]},\n {\"memo\": \"Supplies\", \"lines\": [\n (\"Supplies\", \"D\", \"50.00\"),\n (\"Cash\", \"C\", \"49.99\"),\n ]},\n {\"memo\": \"Refund\", \"lines\": [\n (\"Services Revenue\", \"D\", \"1200.00\"),\n (\"Cash\", \"C\", \"1200.00\"),\n ]},\n ]\n normal_sides = {\n \"Cash\": \"D\",\n \"Services Revenue\": \"C\",\n \"Rent Expense\": \"D\",\n \"Supplies\": \"D\",\n }\n\n ledger, quarantined = post_entries(entries, normal_sides)\n\n print(\"=== T-ACCOUNTS ===\")\n for name in sorted(ledger):\n print(render_t_account(ledger[name]))\n print()\n\n print(\"=== QUARANTINED ENTRIES ===\")\n for q in quarantined:\n print(q)\n print()\n\n balances, total_dr, total_cr, is_balanced = trial_balance(ledger)\n print(\"=== TRIAL BALANCE ===\")\n for name, bal in balances.items():\n side = \"Dr\" if bal > 0 else (\"Cr\" if bal < 0 else \"--\")\n print(f\"{name:<20} {bal:>12} ({side})\")\n print(f\"Total debits: {total_dr}\")\n print(f\"Total credits: {total_cr}\")\n print(f\"Balanced: {is_balanced}\")\n print()\n\n print(\"=== ABNORMAL BALANCES ===\")\n for a in abnormal_balances(ledger, normal_sides):\n print(a)\n\n # Sanity checks against the worked example.\n assert len(quarantined) == 1\n assert quarantined[0][\"index\"] == 2\n assert quarantined[0][\"difference\"] == Decimal(\"0.01\")\n assert balances[\"Cash\"] == Decimal(\"-450.00\")\n assert balances[\"Rent Expense\"] == Decimal(\"250.00\")\n assert balances[\"Services Revenue\"] == Decimal(\"200.00\")\n assert \"Supplies\" not in balances\n assert is_balanced and total_dr == Decimal(\"450.00\") and total_cr == Decimal(\"450.00\")\n flagged = abnormal_balances(ledger, normal_sides)\n assert {a[\"account\"] for a in flagged} == {\"Cash\", \"Services Revenue\"}\n print(\"\\nAll worked-example checks passed.\")"}], "meta": {"idx": 2429, "topic": "general ledger and T-account operations", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2279, "latency_s": 99.4}} +{"prompt": [{"role": "user", "content": "You are given a list of journal entries, each a dict with an 'id' and a list of (account, side, amount) lines, where side is 'D' (debit) or 'C' (credit) and amount is a string representing a monetary value. Build a trial balance: for each account, sum all debit amounts and all credit amounts using Decimal arithmetic, then report the account's net position as ('debit', net) if total debits exceed total credits, ('credit', net) if credits exceed debits, or ('zero', 0) if equal. Additionally, detect imbalanced entries: an entry is imbalanced if the sum of its debit lines differs from the sum of its credit lines, even by a single cent, and you must return the ids of all such entries sorted by the absolute imbalance amount descending (ties broken by id ascending). All monetary outputs must be quantized to 2 decimal places with ROUND_HALF_UP. Given entries = [{'id': 'E1', 'lines': [('Cash','D','100.00'),('Revenue','C','100.00')]}, {'id': 'E2', 'lines': [('Equipment','D','250.00'),('Cash','C','200.00'),('Notes Payable','C','50.00')]}, {'id': 'E3', 'lines': [('Supplies','D','75.55'),('Accounts Payable','C','75.00')]}], the trial balance is {'Accounts Payable': ('credit', Decimal('75.00')), 'Cash': ('credit', Decimal('150.00')), 'Equipment': ('debit', Decimal('250.00')), 'Notes Payable': ('credit', Decimal('50.00')), 'Revenue': ('credit', Decimal('100.00')), 'Supplies': ('debit', Decimal('75.55'))}, the imbalanced entry ids are ['E3'] (imbalance 0.55), and the overall trial balance total debits (425.55) do not equal total credits (425.00), which must also be flagged. Implement build_trial_balance(entries) returning a dict with keys 'trial_balance' (account -> (side, net Decimal)), 'imbalanced_ids' (list), 'total_debits', 'total_credits' (quantized Decimals), and 'is_balanced' (bool, True only if total_debits == total_credits and no imbalanced entries exist)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _to_money(value):\n \"\"\"Convert a value to a Decimal quantized to 2 places, ROUND_HALF_UP.\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef build_trial_balance(entries):\n \"\"\"\n Build a trial balance from journal entries and detect imbalances.\n\n Each entry is a dict: {'id': , 'lines': [(account, side, amount), ...]}\n where side is 'D' (debit) or 'C' (credit) and amount is a string/number.\n\n Returns a dict with:\n 'trial_balance': {account: (side, net Decimal)} where side in\n ('debit', 'credit', 'zero'); accounts sorted not required.\n 'imbalanced_ids': ids of entries whose debits != credits, ordered by\n absolute imbalance descending, ties by id ascending.\n 'total_debits': Decimal sum of all debit lines, quantized to cents.\n 'total_credits': Decimal sum of all credit lines, quantized to cents.\n 'is_balanced': True only if totals match and every entry balances.\n \"\"\"\n account_debits = {}\n account_credits = {}\n imbalanced = [] # list of (abs_imbalance, id)\n\n for entry in entries:\n entry_id = entry['id']\n debit_sum = Decimal('0')\n credit_sum = Decimal('0')\n for account, side, amount in entry['lines']:\n amt = _to_money(amount)\n if side == 'D':\n debit_sum += amt\n account_debits[account] = account_debits.get(account, Decimal('0')) + amt\n elif side == 'C':\n credit_sum += amt\n account_credits[account] = account_credits.get(account, Decimal('0')) + amt\n else:\n raise ValueError(\n \"Invalid side {!r} in entry {!r}: must be 'D' or 'C'\".format(side, entry_id)\n )\n imbalance = debit_sum - credit_sum\n if imbalance != 0:\n imbalanced.append((abs(imbalance), entry_id))\n\n # Trial balance per account\n trial_balance = {}\n all_accounts = set(account_debits) | set(account_credits)\n for account in all_accounts:\n d = account_debits.get(account, Decimal('0'))\n c = account_credits.get(account, Decimal('0'))\n net = _to_money(d - c)\n if net > 0:\n trial_balance[account] = ('debit', net)\n elif net < 0:\n trial_balance[account] = ('credit', -net)\n else:\n trial_balance[account] = ('zero', _to_money(Decimal('0')))\n\n total_debits = _to_money(sum(account_debits.values(), Decimal('0')))\n total_credits = _to_money(sum(account_credits.values(), Decimal('0')))\n\n # Sort imbalanced ids: by abs imbalance desc, then id asc.\n imbalanced.sort(key=lambda item: (-item[0], item[1]))\n imbalanced_ids = [entry_id for _, entry_id in imbalanced]\n\n is_balanced = (total_debits == total_credits) and (len(imbalanced_ids) == 0)\n\n return {\n 'trial_balance': trial_balance,\n 'imbalanced_ids': imbalanced_ids,\n 'total_debits': total_debits,\n 'total_credits': total_credits,\n 'is_balanced': is_balanced,\n }\n\n\nif __name__ == '__main__':\n entries = [\n {'id': 'E1', 'lines': [('Cash', 'D', '100.00'), ('Revenue', 'C', '100.00')]},\n {'id': 'E2', 'lines': [('Equipment', 'D', '250.00'),\n ('Cash', 'C', '200.00'),\n ('Notes Payable', 'C', '50.00')]},\n {'id': 'E3', 'lines': [('Supplies', 'D', '75.55'),\n ('Accounts Payable', 'C', '75.00')]},\n ]\n result = build_trial_balance(entries)\n for account in sorted(result['trial_balance']):\n side, net = result['trial_balance'][account]\n print('{}: {} {}'.format(account, side, net))\n print('Imbalanced ids:', result['imbalanced_ids'])\n print('Total debits: ', result['total_debits'])\n print('Total credits:', result['total_credits'])\n print('Is balanced: ', result['is_balanced'])\n # Sanity check against the worked example\n assert result['trial_balance']['Accounts Payable'] == ('credit', Decimal('75.00'))\n assert result['trial_balance']['Cash'] == ('credit', Decimal('150.00'))\n assert result['trial_balance']['Equipment'] == ('debit', Decimal('250.00'))\n assert result['trial_balance']['Notes Payable'] == ('credit', Decimal('50.00'))\n assert result['trial_balance']['Revenue'] == ('credit', Decimal('100.00'))\n assert result['trial_balance']['Supplies'] == ('debit', Decimal('75.55'))\n assert result['imbalanced_ids'] == ['E3']\n assert result['total_debits'] == Decimal('425.55')\n assert result['total_credits'] == Decimal('425.00')\n assert result['is_balanced'] is False\n print('All assertions passed.')"}], "meta": {"idx": 2439, "topic": "trial balance construction and imbalance detection", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1703, "latency_s": 33.8}} +{"prompt": [{"role": "user", "content": "Write a function `reconcile_petty_cash(log)` that processes a petty cash log and computes the replenishment amount needed to restore the fund to its imprest base. The log is a list of tuples: ('open', base_amount) sets the imprest base (a Decimal, occurs once, first entry); ('expense', description, amount) records cash spent out of the fund; ('topup', amount) records cash added outside of normal replenishment (e.g., a reimbursement). All amounts are Decimals with two decimal places. The function must return a Decimal rounded to two places (ROUND_HALF_UP) representing the replenishment amount: base minus (current cash on hand), where current cash on hand = base - total expenses + total topups. If the resulting replenishment amount is negative (cash on hand exceeds the base), return Decimal('0.00'). Example: log = [('open', Decimal('150.00')), ('expense', 'taxi', Decimal('23.50')), ('expense', 'stamps', Decimal('6.25')), ('topup', Decimal('5.00')), ('expense', 'lunch', Decimal('12.00'))] -> cash on hand = 150.00 - 41.75 + 5.00 = 113.25, so replenishment = 150.00 - 113.25 = Decimal('36.75'). Raise ValueError if the log is empty, if it does not start with an 'open' entry, if any amount is negative, or if an unknown entry type appears."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef reconcile_petty_cash(log):\n if not log:\n raise ValueError('petty cash log is empty')\n\n if log[0][0] != 'open':\n raise ValueError(\"log must start with an 'open' entry\")\n\n base = log[0][1]\n if base < 0:\n raise ValueError('amounts must be non-negative')\n\n expenses = Decimal('0.00')\n topups = Decimal('0.00')\n\n for entry in log[1:]:\n kind = entry[0]\n if kind == 'expense':\n amount = entry[2]\n elif kind == 'topup':\n amount = entry[1]\n else:\n raise ValueError('unknown entry type: {}'.format(kind))\n\n if amount < 0:\n raise ValueError('amounts must be non-negative')\n\n if kind == 'expense':\n expenses += amount\n else:\n topups += amount\n\n cash_on_hand = base - expenses + topups\n replenishment = base - cash_on_hand\n\n if replenishment < 0:\n replenishment = Decimal('0.00')\n\n return replenishment.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n log = [\n ('open', Decimal('150.00')),\n ('expense', 'taxi', Decimal('23.50')),\n ('expense', 'stamps', Decimal('6.25')),\n ('topup', Decimal('5.00')),\n ('expense', 'lunch', Decimal('12.00')),\n ]\n print(reconcile_petty_cash(log)) # 36.75"}], "meta": {"idx": 2433, "topic": "petty cash logs and replenishment", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 686, "latency_s": 103.7}} +{"prompt": [{"role": "user", "content": "You are building a monthly amortization schedule for a fixed-rate mortgage. Given a loan principal P, an annual nominal interest rate r (as a percentage, e.g. 6.5 for 6.5%), and a term of n months, write a function `amortization_schedule(principal, annual_rate_pct, months)` that returns a list of ledger entries, one per payment, as tuples `(payment_number, payment_amount, interest_portion, principal_portion, remaining_balance)`. All money amounts must be computed with `decimal.Decimal` and rounded to cents (ROUND_HALF_UP) at each payment step: the payment amount is computed once and rounded to cents, then each month the interest portion is `balance * (r/12)` rounded to cents, and the principal portion is `payment - interest`. The final payment must be adjusted (if needed) so the remaining balance is exactly zero. Example: principal 100000, rate 6.0, months 12 -> payment 8606.64, first entry interest 500.00, principal 8106.64, balance 91893.36, and the 12th entry has remaining_balance equal to Decimal('0.00'). Return the schedule as a list of tuples of Decimals and ints."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _round(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortization_schedule(principal, annual_rate_pct, months):\n P = Decimal(str(principal))\n monthly_rate = Decimal(str(annual_rate_pct)) / Decimal('100') / Decimal('12')\n n = int(months)\n if n <= 0:\n return []\n if monthly_rate == 0:\n payment = _round(P / Decimal(n))\n else:\n factor = (Decimal(1) + monthly_rate) ** n\n payment = _round(P * monthly_rate * factor / (factor - Decimal(1)))\n balance = P\n schedule = []\n for k in range(1, n + 1):\n interest = _round(balance * monthly_rate)\n if k == n:\n # Final payment: pay off remaining balance exactly\n principal_portion = balance\n payment_amount = _round(balance + interest)\n else:\n principal_portion = _round(payment - interest)\n # Ensure we never overpay before the last payment\n if principal_portion > balance:\n principal_portion = balance\n payment_amount = _round(interest + principal_portion)\n balance = _round(balance - principal_portion)\n schedule.append((k, payment_amount, interest, principal_portion, balance))\n return schedule\n\nif __name__ == '__main__':\n s = amortization_schedule(100000, 6.0, 12)\n for row in s:\n print(row)\n assert s[0][1] == Decimal('8606.64')\n assert s[0][2] == Decimal('500.00')\n assert s[0][3] == Decimal('8106.64')\n assert s[0][4] == Decimal('91893.36')\n assert s[-1][4] == Decimal('0.00')"}], "meta": {"idx": 2440, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 696, "latency_s": 23.0}} +{"prompt": [{"role": "user", "content": "Write a function `validate_journal_entry(entry)` that checks whether a journal entry follows double-entry bookkeeping rules. The entry is a dict with keys 'description' (str) and 'lines', where lines is a list of dicts each having 'account' (str), 'debit' (str), and 'credit' (str) representing money amounts as decimal strings like '100.00'. The entry is valid if: (1) it has at least two lines, (2) each line has at most one of debit or credit non-zero, (3) all amounts are non-negative, and (4) the total of all debits equals the total of all credits exactly (no rounding tolerance). Use `decimal.Decimal` for exact arithmetic. Return True if valid, otherwise False. For example, entry = {'description': 'Buy supplies with cash', 'lines': [{'account': 'Supplies', 'debit': '50.00', 'credit': '0'}, {'account': 'Cash', 'debit': '0', 'credit': '50.00'}]} returns True because debits total 50.00 and credits total 50.00, while an entry where debits total 50.00 and credits total 50.01 returns False."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef validate_journal_entry(entry):\n \"\"\"Return True if the journal entry satisfies double-entry rules.\"\"\"\n lines = entry.get('lines', [])\n if len(lines) < 2:\n return False\n\n zero = Decimal('0')\n total_debits = zero\n total_credits = zero\n\n for line in lines:\n try:\n debit = Decimal(str(line.get('debit', '0')))\n credit = Decimal(str(line.get('credit', '0')))\n except Exception:\n return False\n\n if debit < zero or credit < zero:\n return False\n if debit != zero and credit != zero:\n return False\n\n total_debits += debit\n total_credits += credit\n\n return total_debits == total_credits\n\n\nif __name__ == '__main__':\n valid_entry = {\n 'description': 'Buy supplies with cash',\n 'lines': [\n {'account': 'Supplies', 'debit': '50.00', 'credit': '0'},\n {'account': 'Cash', 'debit': '0', 'credit': '50.00'},\n ],\n }\n invalid_entry = {\n 'description': 'Buy supplies with cash',\n 'lines': [\n {'account': 'Supplies', 'debit': '50.00', 'credit': '0'},\n {'account': 'Cash', 'debit': '0', 'credit': '50.01'},\n ],\n }\n print(validate_journal_entry(valid_entry)) # True\n print(validate_journal_entry(invalid_entry)) # False"}], "meta": {"idx": 2437, "topic": "double-entry journal entries and posting rules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 613, "latency_s": 89.4}} +{"prompt": [{"role": "user", "content": "Write a function `validate_and_post(entries)` that validates and posts double-entry journal entries. Each entry is a dict with keys 'description' (str), 'lines' (list of tuples (account, debit, credit)) where debit and credit are strings representing money, and accounts are strings. The function must validate that (1) every line has at least one of debit/credit non-zero but not both non-zero, (2) total debits equal total credits using Decimal arithmetic with exactly 2-decimal quantization, and (3) every account name is non-empty. If any entry is invalid, raise ValueError with a message naming the entry description. If all entries are valid, return a dict mapping each account to its net balance (debits minus credits), quantized to 2 decimal places. Example: entries = [{'description': 'Buy supplies', 'lines': [('cash', '50.00', ''), ('supplies', '', '50.00')]}] should raise ValueError because debits and credits do not balance (cash is debited 50.00 but supplies is credited 50.00, so debits=50.00 and credits=50.00 balance? no: cash debit 50.00, supplies credit 50.00 does balance). Corrected example: entries = [{'description': 'Buy supplies', 'lines': [('cash', '50.00', ''), ('supplies', '', '25.00')]}] raises ValueError('Unbalanced entry: Buy supplies'), while entries = [{'description': 'Sale', 'lines': [('cash', '75.50', ''), ('revenue', '', '75.50')]}] returns {'cash': Decimal('75.50'), 'revenue': Decimal('-75.50')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _to_amount(value):\n if value is None or value == '' or value == '0':\n return Decimal('0.00')\n return Decimal(value).quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef validate_and_post(entries):\n balances = {}\n for entry in entries:\n description = entry.get('description', '')\n lines = entry.get('lines', [])\n if not lines:\n raise ValueError('Entry has no lines: %s' % description)\n total_debits = Decimal('0.00')\n total_credits = Decimal('0.00')\n for account, debit, credit in lines:\n if not account or not isinstance(account, str) or account.strip() == '':\n raise ValueError('Invalid account name in entry: %s' % description)\n d = _to_amount(debit)\n c = _to_amount(credit)\n if d != 0 and c != 0:\n raise ValueError('Line has both debit and credit in entry: %s' % description)\n if d == 0 and c == 0:\n raise ValueError('Line has zero amount in entry: %s' % description)\n total_debits += d\n total_credits += c\n if total_debits != total_credits:\n raise ValueError('Unbalanced entry: %s' % description)\n for account, debit, credit in lines:\n d = _to_amount(debit)\n c = _to_amount(credit)\n balances[account] = balances.get(account, Decimal('0.00')) + d - c\n return {account: balance.quantize(TWO, rounding=ROUND_HALF_UP)\n for account, balance in balances.items()}\n\n\nif __name__ == '__main__':\n good = [{'description': 'Sale',\n 'lines': [('cash', '75.50', ''), ('revenue', '', '75.50')]}]\n print(validate_and_post(good))\n try:\n bad = [{'description': 'Buy supplies',\n 'lines': [('cash', '50.00', ''), ('supplies', '', '25.00')]}]\n validate_and_post(bad)\n except ValueError as exc:\n print('ValueError:', exc)"}], "meta": {"idx": 2442, "topic": "double-entry journal entries and posting rules", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 880, "latency_s": 8.8}} +{"prompt": [{"role": "user", "content": "A company's fiscal year begins in a configurable month (1\u201312) rather than always January; for example, with fiscal_start_month=4 and year=2024 the fiscal year runs from 2024-04-01 through 2025-03-31, and its four fiscal quarters end on the last calendar day of Jun 2024, Sep 2024, Dec 2024, and Mar 2025 (leap years such as Feb 2024 must be handled correctly). You are given a ledger as a list of (iso_date, account, amount) tuples where amount is a string parsed with decimal.Decimal, debits are positive, and credits are negative; entries dated outside the fiscal year must be ignored. Implement helpers end_of_month(year, month) returning the last calendar day of a month as a datetime.date, and fiscal_quarters(fiscal_start_month, year) returning the four (quarter_start, quarter_end) date pairs in order. Write a function fiscal_quarter_report(entries, fiscal_start_month, year) that returns, for each fiscal quarter Q1\u2013Q4 in order, a tuple (label, quarter_end_iso, balances), where balances is an alphabetically sorted list of (account, rounded_balance) pairs giving each account's cumulative net amount over all in-year entries dated up to and including that quarter's end, with each balance rounded to cents using ROUND_HALF_UP. Worked example: entries = [(\"2024-04-10\",\"Cash\",\"500.00\"), (\"2024-06-30\",\"Revenue\",\"-500.00\"), (\"2024-07-01\",\"Cash\",\"100.005\"), (\"2024-12-31\",\"Expenses\",\"250.25\"), (\"2025-02-28\",\"Revenue\",\"-75.10\"), (\"2024-03-31\",\"Cash\",\"999.99\")] with fiscal_start_month=4, year=2024 must produce [(\"Q1\",\"2024-06-30\",[(\"Cash\",Decimal(\"500.00\")),(\"Revenue\",Decimal(\"-500.00\"))]), (\"Q2\",\"2024-09-30\",[(\"Cash\",Decimal(\"600.01\")),(\"Revenue\",Decimal(\"-500.00\"))]), (\"Q3\",\"2024-12-31\",[(\"Cash\",Decimal(\"600.01\")),(\"Expenses\",Decimal(\"250.25\")),(\"Revenue\",Decimal(\"-500.00\"))]), (\"Q4\",\"2025-03-31\",[(\"Cash\",Decimal(\"600.01\")),(\"Expenses\",Decimal(\"250.25\")),(\"Revenue\",Decimal(\"-575.10\"))])], where the 2024-03-31 entry is dropped as falling before the fiscal year and the 600.005 Cash balance rounds up to 600.01."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\ndef end_of_month(year, month):\n \"\"\"Return the last calendar day of (year, month) as a datetime.date.\"\"\"\n if not 1 <= month <= 12:\n raise ValueError(\"month must be 1..12\")\n last_day = calendar.monthrange(year, month)[1]\n return date(year, month, last_day)\n\n\ndef _shift_month(year, month, offset):\n \"\"\"Shift (year, month) forward by `offset` months, handling rollover.\"\"\"\n total = year * 12 + (month - 1) + offset\n return total // 12, total % 12 + 1\n\n\ndef fiscal_year_bounds(fiscal_start_month, year):\n \"\"\"Return (start_date, end_date) of the fiscal year beginning in the\n given month of the given calendar year.\"\"\"\n if not 1 <= fiscal_start_month <= 12:\n raise ValueError(\"fiscal_start_month must be 1..12\")\n start = date(year, fiscal_start_month, 1)\n if fiscal_start_month == 1:\n end = end_of_month(year, 12)\n else:\n end_year, end_month = _shift_month(year, fiscal_start_month, 11)\n end = end_of_month(end_year, end_month)\n return start, end\n\n\ndef fiscal_quarters(fiscal_start_month, year):\n \"\"\"Return the four (quarter_start, quarter_end) date pairs of the fiscal year.\"\"\"\n quarters = []\n for k in range(4):\n sy, sm = _shift_month(year, fiscal_start_month, 3 * k)\n ey, em = _shift_month(year, fiscal_start_month, 3 * k + 2)\n quarters.append((date(sy, sm, 1), end_of_month(ey, em)))\n return quarters\n\n\ndef fiscal_quarter_report(entries, fiscal_start_month, year):\n \"\"\"Build cumulative per-account quarter-end balances for one fiscal year.\n\n entries: iterable of (iso_date_str, account, amount_str) tuples.\n Returns a list of (\"Qk\", quarter_end_iso, [(account, Decimal), ...]).\n \"\"\"\n fy_start, fy_end = fiscal_year_bounds(fiscal_start_month, year)\n\n parsed = []\n for iso_date, account, amount in entries:\n d = date.fromisoformat(iso_date)\n if fy_start <= d <= fy_end:\n parsed.append((d, account, Decimal(amount)))\n parsed.sort(key=lambda e: e[0])\n\n report = []\n for k, (_q_start, q_end) in enumerate(\n fiscal_quarters(fiscal_start_month, year), start=1\n ):\n balances = {}\n for d, account, amount in parsed:\n if d <= q_end:\n balances[account] = balances.get(account, Decimal(\"0\")) + amount\n rounded = [\n (account, balances[account].quantize(CENT, rounding=ROUND_HALF_UP))\n for account in sorted(balances)\n ]\n report.append((f\"Q{k}\", q_end.isoformat(), rounded))\n return report\n\n\nif __name__ == \"__main__\":\n # Sanity checks for date utilities (leap-year handling included).\n assert end_of_month(2024, 2) == date(2024, 2, 29)\n assert end_of_month(2025, 2) == date(2025, 2, 28)\n assert end_of_month(2024, 12) == date(2024, 12, 31)\n assert fiscal_quarters(4, 2024) == [\n (date(2024, 4, 1), date(2024, 6, 30)),\n (date(2024, 7, 1), date(2024, 9, 30)),\n (date(2024, 10, 1), date(2024, 12, 31)),\n (date(2025, 1, 1), date(2025, 3, 31)),\n ]\n\n entries = [\n (\"2024-04-10\", \"Cash\", \"500.00\"),\n (\"2024-06-30\", \"Revenue\", \"-500.00\"),\n (\"2024-07-01\", \"Cash\", \"100.005\"),\n (\"2024-12-31\", \"Expenses\", \"250.25\"),\n (\"2025-02-28\", \"Revenue\", \"-75.10\"),\n (\"2024-03-31\", \"Cash\", \"999.99\"), # before the fiscal year: ignored\n ]\n\n result = fiscal_quarter_report(entries, 4, 2024)\n expected = [\n (\"Q1\", \"2024-06-30\", [(\"Cash\", Decimal(\"500.00\")), (\"Revenue\", Decimal(\"-500.00\"))]),\n (\"Q2\", \"2024-09-30\", [(\"Cash\", Decimal(\"600.01\")), (\"Revenue\", Decimal(\"-500.00\"))]),\n (\"Q3\", \"2024-12-31\", [(\"Cash\", Decimal(\"600.01\")), (\"Expenses\", Decimal(\"250.25\")), (\"Revenue\", Decimal(\"-500.00\"))]),\n (\"Q4\", \"2025-03-31\", [(\"Cash\", Decimal(\"600.01\")), (\"Expenses\", Decimal(\"250.25\")), (\"Revenue\", Decimal(\"-575.10\"))]),\n ]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2438, "topic": "fiscal periods, quarters, and month-end date utilities", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1609, "latency_s": 101.2}} +{"prompt": [{"role": "user", "content": "Write a function reconcile(ledger_lines, statement_lines) that reconciles a company's cash ledger against its bank statement, where each line has the form 'YYYY-MM-DD|description|amount' and amount is a decimal string (negative for outflows) that must be parsed with Decimal and quantized to cents using ROUND_HALF_UP. First detect reversal pairs on the statement: an entry pairs with the earliest later still-unpaired entry carrying the exact opposite amount within 3 calendar days, and both are excluded from matching and reported. Then match ledger entries to the remaining statement entries in three passes, using each entry at most once and preferring earlier passes: (1) exact \u2014 equal amount, equal date, equal normalized description (case-insensitive, whitespace collapsed); (2) timing \u2014 equal amount, equal normalized description, dates at most 2 days apart; (3) transposition \u2014 equal date, same sign, and the absolute cent values differ by exactly one adjacent digit swap (e.g. 1500.00 vs 5100.00). Afterward, report unmatched entries from both sides, flag any unmatched ledger entries that share (date, normalized description, amount) with another unmatched ledger entry as duplicates, and compute book_balance, bank_balance (over all statement lines including reversals), and difference = bank_balance \u2212 book_balance. Return a dict with keys 'matched' (list of {'ledger': entry, 'statement': entry, 'match_type': ...}), 'reversal_pairs', 'unmatched_ledger', 'unmatched_statement', 'duplicate_ledger_entries', 'book_balance', 'bank_balance', 'difference', where every entry is rendered as {'date': ISO string, 'description': original text, 'amount': string} and balances are strings. Worked example: ledger ['2024-01-02|Office Supplies|-125.50','2024-01-03|Client Payment|3200.00','2024-01-05|Rent|-5100.00','2024-01-05|Rent|-1500.00','2024-01-09|Utility Bill|-89.99','2024-01-09|Utility Bill|-89.99'] versus statement ['2024-01-02|Office Supplies|-125.50','2024-01-04|Client Payment|3200.00','2024-01-05|Rent Payment|-1500.00','2024-01-08|Wire Transfer|750.00','2024-01-09|Wire Reversal|-750.00','2024-01-10|Bank Fee|-15.00'] must produce matches of types exact, timing, transposition (in that order), one reversal pair (Wire Transfer/Wire Reversal), unmatched ledger entries Rent -1500.00 and the two Utility Bills -89.99 (both flagged as duplicates), unmatched statement entry Bank Fee -15.00, book_balance '-3705.48', bank_balance '1559.50', and difference '5264.98'."}], "completion": [{"role": "assistant", "content": "import json\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\n\n\ndef _parse_amount(text):\n return Decimal(text.strip()).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _parse_line(line):\n date_str, desc, amt = line.split(\"|\")\n return {\n \"date\": date.fromisoformat(date_str.strip()),\n \"description\": \" \".join(desc.split()).lower(),\n \"amount\": _parse_amount(amt),\n \"raw_description\": desc.strip(),\n }\n\n\ndef _out(entry):\n return {\n \"date\": entry[\"date\"].isoformat(),\n \"description\": entry[\"raw_description\"],\n \"amount\": str(entry[\"amount\"]),\n }\n\n\ndef _is_transposition(a, b):\n if a == b or (a < 0) != (b < 0):\n return False\n sa = str(int(abs(a) * 100))\n sb = str(int(abs(b) * 100))\n if len(sa) != len(sb):\n return False\n return any(\n sa[:i] + sa[i + 1] + sa[i] + sa[i + 2:] == sb\n for i in range(len(sa) - 1)\n )\n\n\ndef _reversal_pairs(statement):\n used = [False] * len(statement)\n pairs = []\n for i, first in enumerate(statement):\n if used[i] or first[\"amount\"] == 0:\n continue\n for j in range(i + 1, len(statement)):\n second = statement[j]\n if used[j] or second[\"amount\"] != -first[\"amount\"]:\n continue\n if 0 <= (second[\"date\"] - first[\"date\"]).days <= 3:\n used[i] = used[j] = True\n pairs.append([first, second])\n break\n remaining = [e for k, e in enumerate(statement) if not used[k]]\n return pairs, remaining\n\n\ndef reconcile(ledger_lines, statement_lines):\n ledger = [_parse_line(x) for x in ledger_lines]\n all_statement = [_parse_line(x) for x in statement_lines]\n pairs, statement = _reversal_pairs(all_statement)\n\n lused = [False] * len(ledger)\n sused = [False] * len(statement)\n matched = []\n\n def run_pass(amount_ok, date_ok, desc_ok, match_type):\n for li, l in enumerate(ledger):\n if lused[li]:\n continue\n for si, s in enumerate(statement):\n if sused[si]:\n continue\n if amount_ok(l, s) and date_ok(l, s) and desc_ok(l, s):\n lused[li] = sused[si] = True\n matched.append({\n \"ledger\": _out(l),\n \"statement\": _out(s),\n \"match_type\": match_type,\n })\n break\n\n run_pass(\n lambda l, s: l[\"amount\"] == s[\"amount\"],\n lambda l, s: l[\"date\"] == s[\"date\"],\n lambda l, s: l[\"description\"] == s[\"description\"],\n \"exact\",\n )\n run_pass(\n lambda l, s: l[\"amount\"] == s[\"amount\"],\n lambda l, s: abs((l[\"date\"] - s[\"date\"]).days) <= 2,\n lambda l, s: l[\"description\"] == s[\"description\"],\n \"timing\",\n )\n run_pass(\n lambda l, s: _is_transposition(l[\"amount\"], s[\"amount\"]),\n lambda l, s: l[\"date\"] == s[\"date\"],\n lambda l, s: True,\n \"transposition\",\n )\n\n unmatched_ledger = [l for k, l in enumerate(ledger) if not lused[k]]\n unmatched_statement = [s for k, s in enumerate(statement) if not sused[k]]\n\n groups = {}\n for l in unmatched_ledger:\n groups.setdefault((l[\"date\"], l[\"description\"], l[\"amount\"]), []).append(l)\n duplicates = [e for v in groups.values() if len(v) > 1 for e in v]\n\n zero = Decimal(\"0.00\")\n book_balance = sum((l[\"amount\"] for l in ledger), zero)\n bank_balance = sum((s[\"amount\"] for s in all_statement), zero)\n difference = bank_balance - book_balance\n\n return {\n \"matched\": matched,\n \"reversal_pairs\": [[_out(a), _out(b)] for a, b in pairs],\n \"unmatched_ledger\": [_out(l) for l in unmatched_ledger],\n \"unmatched_statement\": [_out(s) for s in unmatched_statement],\n \"duplicate_ledger_entries\": [_out(l) for l in duplicates],\n \"book_balance\": str(book_balance),\n \"bank_balance\": str(bank_balance),\n \"difference\": str(difference),\n }\n\n\nif __name__ == \"__main__\":\n ledger_lines = [\n \"2024-01-02|Office Supplies|-125.50\",\n \"2024-01-03|Client Payment|3200.00\",\n \"2024-01-05|Rent|-5100.00\",\n \"2024-01-05|Rent|-1500.00\",\n \"2024-01-09|Utility Bill|-89.99\",\n \"2024-01-09|Utility Bill|-89.99\",\n ]\n statement_lines = [\n \"2024-01-02|Office Supplies|-125.50\",\n \"2024-01-04|Client Payment|3200.00\",\n \"2024-01-05|Rent Payment|-1500.00\",\n \"2024-01-08|Wire Transfer|750.00\",\n \"2024-01-09|Wire Reversal|-750.00\",\n \"2024-01-10|Bank Fee|-15.00\",\n ]\n report = reconcile(ledger_lines, statement_lines)\n print(json.dumps(report, indent=2))\n assert [m[\"match_type\"] for m in report[\"matched\"]] == [\"exact\", \"timing\", \"transposition\"]\n assert len(report[\"reversal_pairs\"]) == 1\n assert len(report[\"unmatched_ledger\"]) == 3\n assert len(report[\"unmatched_statement\"]) == 1\n assert len(report[\"duplicate_ledger_entries\"]) == 2\n assert report[\"book_balance\"] == \"-3705.48\"\n assert report[\"bank_balance\"] == \"1559.50\"\n assert report[\"difference\"] == \"5264.98\"\n print(\"All reconciliation checks passed.\")"}], "meta": {"idx": 2419, "topic": "bank statement reconciliation", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2022, "latency_s": 200.7}} +{"prompt": [{"role": "user", "content": "A small shop sells three items with net prices and VAT rates given as input. Write a program that reads, for each item, a net price (a decimal string like '19.99') and a VAT rate in percent (e.g. '7'), computes the VAT amount and the gross price, and prints a simple invoice report. All money computations must use Decimal with ROUND_HALF_UP rounding to 2 decimal places. For example, with net price '19.99' and VAT rate '7%', the VAT amount is 19.99 * 7 / 100 = 1.3993, which rounds to '1.40', and the gross price is 19.99 + 1.40 = '21.39'. The report should list each item's net, VAT, and gross, then the invoice totals (total net, total VAT, total gross), with each amount formatted to exactly 2 decimal places. Input: first line N, then N lines each with 'price vat_rate'. Output: N lines 'net=X vat=Y gross=Z' followed by a line 'TOTAL net=A vat=B gross=C'."}], "completion": [{"role": "assistant", "content": "import sys\nfrom decimal import Decimal, ROUND_HALF_UP\n\ndef money(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\ndef main():\n data = sys.stdin.read().split()\n n = int(data[0])\n idx = 1\n total_net = Decimal('0')\n total_vat = Decimal('0')\n total_gross = Decimal('0')\n lines = []\n for _ in range(n):\n net = Decimal(data[idx]); rate = Decimal(data[idx + 1]); idx += 2\n vat = money(net * rate / Decimal('100'))\n gross = money(net + vat)\n total_net += money(net)\n total_vat += vat\n total_gross += gross\n lines.append(f\"net={money(net)} vat={vat} gross={gross}\")\n lines.append(f\"TOTAL net={money(total_net)} vat={money(total_vat)} gross={money(total_gross)}\")\n print('\\n'.join(lines))\n\nif __name__ == '__main__':\n main()"}], "meta": {"idx": 2447, "topic": "sales tax and VAT computation and rounding", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 437, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "Write a function `compute_net_pay(gross, fed_rate, state_rate, pretax_deductions)` that computes an employee's net pay for one pay period. The gross pay and each pretax deduction are given as strings or Decimals representing money. Pretax deductions (such as a 401k contribution or health premium) reduce taxable gross before taxes are applied. Federal and state tax rates are given as Decimal fractions (e.g. Decimal('0.12') for 12%), and each tax amount must be rounded to the nearest cent using ROUND_HALF_UP. Net pay equals taxable gross minus federal tax, state tax, and any posttax flat fee of $5.00 for a payroll processing charge. Return a Decimal rounded to 2 places with ROUND_HALF_UP. Example: gross='2000.00', fed_rate=Decimal('0.12'), state_rate=Decimal('0.05'), pretax_deductions=[Decimal('150.00'), Decimal('50.00')] gives taxable gross 1800.00, federal tax 216.00, state tax 90.00, net pay 1800.00 - 216.00 - 90.00 - 5.00 = 1489.00. Raise ValueError if any amount is negative or if gross is less than total pretax deductions."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\nPROCESSING_FEE = Decimal('5.00')\n\n\ndef _money(x):\n return Decimal(str(x)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef compute_net_pay(gross, fed_rate, state_rate, pretax_deductions):\n gross = Decimal(str(gross))\n fed_rate = Decimal(str(fed_rate))\n state_rate = Decimal(str(state_rate))\n pretax_deductions = [Decimal(str(d)) for d in (pretax_deductions or [])]\n\n if gross < 0 or fed_rate < 0 or state_rate < 0:\n raise ValueError('gross and tax rates must be non-negative')\n for d in pretax_deductions:\n if d < 0:\n raise ValueError('pretax deductions must be non-negative')\n\n total_pretax = sum(pretax_deductions, Decimal('0'))\n if gross < total_pretax:\n raise ValueError('gross pay cannot be less than pretax deductions')\n\n taxable_gross = _money(gross - total_pretax)\n fed_tax = (taxable_gross * fed_rate).quantize(CENT, rounding=ROUND_HALF_UP)\n state_tax = (taxable_gross * state_rate).quantize(CENT, rounding=ROUND_HALF_UP)\n\n net = taxable_gross - fed_tax - state_tax - PROCESSING_FEE\n return net.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n from decimal import Decimal as D\n result = compute_net_pay('2000.00', D('0.12'), D('0.05'), [D('150.00'), D('50.00')])\n assert result == D('1489.00'), result\n print('Net pay:', result)"}], "meta": {"idx": 2443, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 629, "latency_s": 51.4}} +{"prompt": [{"role": "user", "content": "You are building a multi-currency FX gain/loss report for a bookkeeping system whose base (functional) currency is, say, USD. The input is a list of commands, one per line (blank lines and lines starting with '#' are ignored): 'BASE ' declares the base currency; 'BUY ' acquires foreign currency qty at the given FX rate expressed as base-currency units per one unit of ; 'SELL ' disposes of foreign currency at that rate; 'CLOSE ' gives the period-end closing rate used for revaluation. Foreign-currency positions must be tracked as FIFO lots; when a SELL is executed, the realized FX gain/loss for that currency is (sell qty \u00d7 sell rate) minus the FIFO cost of the consumed lots, and the SELL must never exceed the currently held quantity (raise a ValueError with the message 'Insufficient ' if it does). At period end, the unrealized FX gain/loss per currency is (remaining qty \u00d7 close rate) minus the total book cost of the remaining lots (0 if no close rate was given). All arithmetic must use Decimal with full precision throughout and be rounded exactly once at output time to 2 decimal places using ROUND_HALF_UP. The output must contain, for each currency in order of first appearance, a line ': realized= unrealized= position=

' (position = remaining quantity, 2dp), followed by the lines 'TOTAL realized=', 'TOTAL unrealized=', and 'TOTAL net=' where net = R + U. Worked example: input 'BASE USD / BUY EUR 1000 1.10 / SELL EUR 600 1.15 / BUY GBP 500 1.25 / SELL GBP 200 1.20 / CLOSE EUR 1.12 / CLOSE GBP 1.30' must produce exactly: 'EUR: realized=30.00 unrealized=8.00 position=400.00', 'GBP: realized=-10.00 unrealized=15.00 position=300.00', 'TOTAL realized=20.00', 'TOTAL unrealized=23.00', 'TOTAL net=43.00' (EUR realized = 600\u00d71.15 \u2212 600\u00d71.10 = 30.00; GBP realized = 200\u00d71.20 \u2212 200\u00d71.25 = \u221210.00)."}], "completion": [{"role": "assistant", "content": "import sys\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom collections import deque\n\nTWO = Decimal(\"0.01\")\n\n\ndef q2(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef build_report(lines):\n base = None\n lots = {} # ccy -> deque of (qty, rate) FIFO lots\n order = [] # currencies in order of first appearance\n realized = {} # ccy -> Decimal realized fx gain/loss\n close_rates = {} # ccy -> Decimal closing rate\n\n for raw in lines:\n line = raw.strip()\n if not line or line.startswith(\"#\"):\n continue\n parts = line.split()\n cmd = parts[0].upper()\n\n if cmd == \"BASE\":\n base = parts[1]\n\n elif cmd == \"BUY\":\n ccy, qty, rate = parts[1], Decimal(parts[2]), Decimal(parts[3])\n if ccy not in lots:\n lots[ccy] = deque()\n order.append(ccy)\n lots[ccy].append((qty, rate))\n\n elif cmd == \"SELL\":\n ccy, qty, rate = parts[1], Decimal(parts[2]), Decimal(parts[3])\n dq = lots.get(ccy, deque())\n held = sum(l[0] for l in dq)\n if qty > held:\n raise ValueError(\"Insufficient \" + ccy)\n remaining = qty\n proceeds = qty * rate\n cost = Decimal(0)\n while remaining > 0:\n lqty, lrate = dq[0]\n take = min(remaining, lqty)\n cost += take * lrate\n remaining -= take\n if take == lqty:\n dq.popleft()\n else:\n dq[0] = (lqty - take, lrate)\n realized[ccy] = realized.get(ccy, Decimal(0)) + proceeds - cost\n\n elif cmd == \"CLOSE\":\n close_rates[parts[1]] = Decimal(parts[2])\n\n else:\n raise ValueError(\"Unknown command: \" + cmd)\n\n out = []\n total_realized = Decimal(0)\n total_unrealized = Decimal(0)\n\n for ccy in order:\n pos_qty = sum(l[0] for l in lots[ccy])\n book_cost = sum(l[0] * l[1] for l in lots[ccy])\n unrealized = Decimal(0)\n if ccy in close_rates:\n unrealized = pos_qty * close_rates[ccy] - book_cost\n r = realized.get(ccy, Decimal(0))\n total_realized += r\n total_unrealized += unrealized\n out.append(\n \"%s: realized=%s unrealized=%s position=%s\"\n % (ccy, q2(r), q2(unrealized), q2(pos_qty))\n )\n\n out.append(\"TOTAL realized=%s\" % q2(total_realized))\n out.append(\"TOTAL unrealized=%s\" % q2(total_unrealized))\n out.append(\"TOTAL net=%s\" % q2(total_realized + total_unrealized))\n return out\n\n\nif __name__ == \"__main__\":\n data = sys.stdin.read()\n if not data.strip():\n data = \"\\n\".join([\n \"BASE USD\",\n \"BUY EUR 1000 1.10\",\n \"SELL EUR 600 1.15\",\n \"BUY GBP 500 1.25\",\n \"SELL GBP 200 1.20\",\n \"CLOSE EUR 1.12\",\n \"CLOSE GBP 1.30\",\n ])\n for line in build_report(data.splitlines()):\n print(line)"}], "meta": {"idx": 2445, "topic": "multi-currency conversion and FX gain/loss", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1279, "latency_s": 51.7}} +{"prompt": [{"role": "user", "content": "A petty cash fund starts with a fixed imprest amount and is replenished back to that amount at the end of each period. You are given the opening balance as a string, and a list of expense entries for one period, each a tuple (description, amount_string). Write a function `petty_cash_report(opening: str, expenses: list[tuple[str, str]]) -> dict` that uses `decimal.Decimal` for all money arithmetic and returns a dict with keys: 'total_expenses' (sum of expense amounts, Decimal, rounded to 2 places with ROUND_HALF_UP), 'cash_on_hand' (opening balance minus total expenses, Decimal, rounded to 2 places), 'replenishment' (amount needed to restore the fund to the opening balance, i.e., total_expenses, as a non-negative Decimal rounded to 2 places), and 'entries' (list of dicts with keys 'description' and 'amount', where amount is a Decimal rounded to 2 places). If cash_on_hand would be negative, raise a ValueError with message 'Insufficient petty cash'. Example: petty_cash_report('100.00', [('postage', '4.55'), ('snacks', '12.50'), ('taxi', '8.25')]) returns {'total_expenses': Decimal('25.30'), 'cash_on_hand': Decimal('74.70'), 'replenishment': Decimal('25.30'), 'entries': [{'description': 'postage', 'amount': Decimal('4.55')}, {'description': 'snacks', 'amount': Decimal('12.50')}, {'description': 'taxi', 'amount': Decimal('8.25')}]}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef petty_cash_report(opening: str, expenses: list) -> dict:\n TWO = Decimal('0.01')\n\n def q(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n opening_d = q(Decimal(opening))\n entries = []\n total = Decimal('0.00')\n for description, amount_str in expenses:\n amt = q(Decimal(amount_str))\n if amt < 0:\n raise ValueError('Expense amounts must be non-negative')\n entries.append({'description': description, 'amount': amt})\n total += amt\n total = q(total)\n cash_on_hand = q(opening_d - total)\n if cash_on_hand < 0:\n raise ValueError('Insufficient petty cash')\n replenishment = q(total)\n return {\n 'total_expenses': total,\n 'cash_on_hand': cash_on_hand,\n 'replenishment': replenishment,\n 'entries': entries,\n }\n\n\nif __name__ == '__main__':\n result = petty_cash_report('100.00', [('postage', '4.55'), ('snacks', '12.50'), ('taxi', '8.25')])\n print(result)"}], "meta": {"idx": 2449, "topic": "petty cash logs and replenishment", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 610, "latency_s": 5.9}} +{"prompt": [{"role": "user", "content": "You are given a general ledger as a list of entries, where each entry is a tuple (account, debit, credit) with the account name as a string and the money amounts as strings representing exact decimal values. You are also given a chart of accounts: a dict mapping each account name to one of the categories 'asset', 'liability', 'equity', 'revenue', or 'expense'. Write a function summarize_ledger(entries, chart) that: (1) validates that total debits equal total credits across all entries, raising ValueError otherwise; (2) validates that every account appearing in the entries exists in the chart, raising ValueError otherwise; (3) computes each account's balance using the natural debit/credit direction of its category (assets and expenses increase with debits; liabilities, equity, and revenues increase with credits); (4) returns a dict with keys 'net_income' (revenues minus expenses, i.e. the profit-and-loss figure), 'assets', 'liabilities', 'equity' (the reported balance-sheet equity, which must include net income), and 'balanced', a boolean that is True when assets equal liabilities plus equity. All monetary amounts must be handled with the decimal.Decimal type and rounded to two decimal places with ROUND_HALF_UP. For example, given entries [('Cash','10000','0'), ('Contributed Capital','0','10000'), ('Inventory','2000','0'), ('Cash','0','2000'), ('Sales Revenue','0','3500'), ('Cash','3500','0'), ('COGS','1000','0'), ('Inventory','0','1000'), ('Rent Expense','500','0'), ('Cash','0','500')] and a chart classifying Cash and Inventory as assets, Contributed Capital as equity, Sales Revenue as revenue, and COGS and Rent Expense as expenses, the function must return {'net_income': Decimal('2000.00'), 'assets': Decimal('12000.00'), 'liabilities': Decimal('0.00'), 'equity': Decimal('12000.00'), 'balanced': True}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef summarize_ledger(entries, chart):\n \"\"\"Summarize a general ledger into P&L and balance-sheet figures.\n\n entries: iterable of (account, debit, credit) where amounts are strings.\n chart: dict mapping account name -> one of\n 'asset', 'liability', 'equity', 'revenue', 'expense'.\n\n Returns a dict with net_income, assets, liabilities, equity (including\n net income), and a 'balanced' boolean. All amounts are Decimal values\n rounded to two decimal places (ROUND_HALF_UP).\n \"\"\"\n CENT = Decimal('0.01')\n\n def to_money(value):\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\n DEBIT_CATEGORIES = {'asset', 'expense'}\n CREDIT_CATEGORIES = {'liability', 'equity', 'revenue'}\n VALID_CATEGORIES = DEBIT_CATEGORIES | CREDIT_CATEGORIES\n\n total_debits = Decimal('0')\n total_credits = Decimal('0')\n account_balances = {}\n\n for account, debit_str, credit_str in entries:\n if account not in chart:\n raise ValueError('unknown account in ledger: {!r}'.format(account))\n category = chart[account]\n if category not in VALID_CATEGORIES:\n raise ValueError(\n 'invalid category {!r} for account {!r}'.format(category, account)\n )\n\n debit = Decimal(debit_str)\n credit = Decimal(credit_str)\n if debit < 0 or credit < 0:\n raise ValueError('negative amount in entry for {!r}'.format(account))\n\n total_debits += debit\n total_credits += credit\n\n if category in DEBIT_CATEGORIES:\n signed_change = debit - credit\n else:\n signed_change = credit - debit\n\n account_balances[account] = account_balances.get(account, Decimal('0')) + signed_change\n\n if total_debits != total_credits:\n raise ValueError(\n 'ledger is out of balance: debits {} != credits {}'.format(\n total_debits, total_credits\n )\n )\n\n totals = {\n 'asset': Decimal('0'),\n 'liability': Decimal('0'),\n 'equity': Decimal('0'),\n 'revenue': Decimal('0'),\n 'expense': Decimal('0'),\n }\n for account, balance in account_balances.items():\n totals[chart[account]] += balance\n\n net_income = totals['revenue'] - totals['expense']\n reported_equity = totals['equity'] + net_income\n\n return {\n 'net_income': to_money(net_income),\n 'assets': to_money(totals['asset']),\n 'liabilities': to_money(totals['liability']),\n 'equity': to_money(reported_equity),\n 'balanced': to_money(totals['asset'])\n == to_money(totals['liability'] + reported_equity),\n }\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', '10000', '0'),\n ('Contributed Capital', '0', '10000'),\n ('Inventory', '2000', '0'),\n ('Cash', '0', '2000'),\n ('Sales Revenue', '0', '3500'),\n ('Cash', '3500', '0'),\n ('COGS', '1000', '0'),\n ('Inventory', '0', '1000'),\n ('Rent Expense', '500', '0'),\n ('Cash', '0', '500'),\n ]\n chart = {\n 'Cash': 'asset',\n 'Inventory': 'asset',\n 'Contributed Capital': 'equity',\n 'Sales Revenue': 'revenue',\n 'COGS': 'expense',\n 'Rent Expense': 'expense',\n }\n result = summarize_ledger(entries, chart)\n print(result)\n assert result == {\n 'net_income': Decimal('2000.00'),\n 'assets': Decimal('12000.00'),\n 'liabilities': Decimal('0.00'),\n 'equity': Decimal('12000.00'),\n 'balanced': True,\n }"}], "meta": {"idx": 2446, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "medium", "provider": "novita", "in_tokens": 204, "out_tokens": 1994, "latency_s": 17.2}} +{"prompt": [{"role": "user", "content": "You are given a list of journal entries for a double-entry ledger. Each entry is a tuple (date, account, debit, credit), where debit and credit are strings representing monetary amounts (e.g. '100.00'). Write a function validate_and_post(entries) that (1) validates each entry: debit and credit must be non-negative Decimal amounts, at most one of debit/credit may be non-zero per line, and amounts must be quantized to 2 decimal places; (2) validates the journal as a whole: for each entry id (group of lines sharing the same date and a shared entry number, given as the 5th tuple element), total debits must equal total credits; (3) if any rule is violated, raise ValueError with a message describing the first problem found; otherwise post all lines to a ledger and return an OrderedDict mapping each account to its ending balance (credit-positive, debit-negative), with balances quantized to 2 decimals. Input example: entries = [('2024-01-05', 'Cash', '150.00', '0', 1), ('2024-01-05', 'Revenue', '0', '150.00', 1), ('2024-01-06', 'Rent Expense', '60.00', '0', 2), ('2024-01-06', 'Cash', '0', '60.00', 2)] should return {'Cash': Decimal('90.00'), 'Revenue': Decimal('-150.00'), 'Rent Expense': Decimal('60.00')}. An entry where debits do not equal credits (e.g. entry 3 with only a debit of '10.00' and no credit line) must raise ValueError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, InvalidOperation, ROUND_HALF_UP\nfrom collections import OrderedDict\n\nTWO = Decimal('0.01')\n\ndef _parse_amount(value):\n try:\n amount = Decimal(value)\n except (InvalidOperation, TypeError):\n raise ValueError(\"Invalid amount: {!r}\".format(value))\n if amount < 0:\n raise ValueError(\"Negative amount not allowed: {!r}\".format(value))\n return amount.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef validate_and_post(entries):\n # Step 1: validate individual lines\n parsed = []\n for line in entries:\n if len(line) != 5:\n raise ValueError(\"Each line must have 5 fields\")\n date, account, debit_s, credit_s, entry_no = line\n debit = _parse_amount(debit_s)\n credit = _parse_amount(credit_s)\n if debit > 0 and credit > 0:\n raise ValueError(\"Both debit and credit non-zero on line: {!r}\".format(line))\n if debit == 0 and credit == 0:\n raise ValueError(\"Both debit and credit are zero on line: {!r}\".format(line))\n parsed.append((date, account, debit, credit, entry_no))\n\n # Step 2: validate balance per entry group\n groups = {}\n for date, account, debit, credit, entry_no in parsed:\n groups.setdefault((date, entry_no), []).append((debit, credit))\n for (date, entry_no), lines in groups.items():\n total_debits = sum(d for d, c in lines)\n total_credits = sum(c for d, c in lines)\n if total_debits != total_credits:\n raise ValueError(\n \"Unbalanced entry {} on {}: debits {} != credits {}\".format(\n entry_no, date, total_debits, total_credits))\n\n # Step 3: post to ledger (credit-positive, debit-negative)\n ledger = OrderedDict()\n for date, account, debit, credit, entry_no in parsed:\n ledger[account] = ledger.get(account, Decimal('0.00')) - debit + credit\n\n return OrderedDict(\n (account, balance.quantize(TWO, rounding=ROUND_HALF_UP))\n for account, balance in ledger.items())\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-05', 'Cash', '150.00', '0', 1),\n ('2024-01-05', 'Revenue', '0', '150.00', 1),\n ('2024-01-06', 'Rent Expense', '60.00', '0', 2),\n ('2024-01-06', 'Cash', '0', '60.00', 2),\n ]\n result = validate_and_post(entries)\n print(dict(result))\n bad = entries + [('2024-01-07', 'Supplies', '10.00', '0', 3)]\n try:\n validate_and_post(bad)\n except ValueError as e:\n print('ValueError:', e)"}], "meta": {"idx": 2451, "topic": "double-entry journal entries and posting rules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 991, "latency_s": 10.9}} +{"prompt": [{"role": "user", "content": "A small business posts a recurring monthly office-rent expense of 750.00 EUR on the same day each month. Write a function `rent_entries(start_date, months, day_of_month=1, amount='750.00')` that returns a list of (date, Decimal amount) tuples for the posting dates starting at `start_date` (a `datetime.date`) and covering the next `months` postings. Each posting date is the given `day_of_month` of successive calendar months, starting with the month of `start_date` if `start_date.day <= day_of_month`, otherwise the following month. If a month has fewer days than `day_of_month`, clamp to the last day of that month (e.g. day 31 in February becomes Feb 28/29). The amount must be a `Decimal` quantized to 2 decimal places with ROUND_HALF_UP. Example: `rent_entries(date(2024, 1, 15), 3, day_of_month=31)` returns `[(date(2024,1,31), Decimal('750.00')), (date(2024,2,29), Decimal('750.00')), (date(2024,3,31), Decimal('750.00'))]`."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\n\ndef rent_entries(start_date, months, day_of_month=1, amount='750.00'):\n quantized = Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n year, month = start_date.year, start_date.month\n if start_date.day > day_of_month:\n month += 1\n if month > 12:\n month = 1\n year += 1\n entries = []\n for _ in range(months):\n last_day = calendar.monthrange(year, month)[1]\n day = min(day_of_month, last_day)\n entries.append((date(year, month, day), quantized))\n month += 1\n if month > 12:\n month = 1\n year += 1\n return entries\n\n\nif __name__ == '__main__':\n result = rent_entries(date(2024, 1, 15), 3, day_of_month=31)\n expected = [\n (date(2024, 1, 31), Decimal('750.00')),\n (date(2024, 2, 29), Decimal('750.00')),\n (date(2024, 3, 31), Decimal('750.00')),\n ]\n assert result == expected, result\n print(result)"}], "meta": {"idx": 2452, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 511, "latency_s": 6.8}} +{"prompt": [{"role": "user", "content": "A small agency settles a monthly ledger of sales transactions. Each transaction has a gross amount, a commission rate (as a percentage, e.g. 12.5 means 12.5%), and a tip that is split equally among a number of agents. Write a function `settle_ledger(transactions)` that takes a list of tuples `(gross, commission_pct, tip, agents)` and returns a report as a dict with keys 'total_gross', 'total_commissions', 'total_net' (gross minus commission), 'total_tips', and 'per_agent_tips' (a dict mapping agent name to tip share, where tip agents are named 'agent_1', 'agent_2', ... for the given agent count). All money must be computed with Decimal using ROUND_HALF_UP to 2 decimal places. Tip splits must be allocated so each agent gets an equal share rounded to cents, with any leftover cent(s) from rounding given to the last agent, and the sum of per-agent tips must exactly equal the total tip. Example: for transaction (Decimal('100.00'), 10, Decimal('5.00'), 2), commission is 10.00, net is 90.00, and each of agent_1 and agent_2 gets 2.50. For (Decimal('10.00'), 10, Decimal('1.00'), 3), agent_1 and agent_2 get 0.33 each and agent_3 gets 0.34."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _round2(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef settle_ledger(transactions):\n total_gross = Decimal('0.00')\n total_commissions = Decimal('0.00')\n total_tips = Decimal('0.00')\n per_agent_tips = {}\n\n for gross, commission_pct, tip, agents in transactions:\n gross = Decimal(str(gross))\n tip = Decimal(str(tip))\n commission = _round2(gross * Decimal(str(commission_pct)) / Decimal('100'))\n\n total_gross += gross\n total_commissions += commission\n total_tips += tip\n\n # Split tip equally, leftover cents to the last agent.\n base_share = _round2(tip / Decimal(agents))\n allocated = base_share * (agents - 1)\n last_share = tip - allocated\n for i in range(1, agents):\n name = 'agent_{}'.format(i)\n per_agent_tips[name] = _round2(per_agent_tips.get(name, Decimal('0.00')) + base_share)\n last_name = 'agent_{}'.format(agents)\n per_agent_tips[last_name] = _round2(per_agent_tips.get(last_name, Decimal('0.00')) + last_share)\n\n total_net = total_gross - total_commissions\n\n return {\n 'total_gross': _round2(total_gross),\n 'total_commissions': _round2(total_commissions),\n 'total_net': _round2(total_net),\n 'total_tips': _round2(total_tips),\n 'per_agent_tips': per_agent_tips,\n }\n\nif __name__ == '__main__':\n txns = [\n (Decimal('100.00'), 10, Decimal('5.00'), 2),\n (Decimal('10.00'), 10, Decimal('1.00'), 3),\n ]\n print(settle_ledger(txns))"}], "meta": {"idx": 2453, "topic": "commission, tip, and percentage splits", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 713, "latency_s": 8.3}} +{"prompt": [{"role": "user", "content": "Write a function `variance_report(budget, actual)` that compares a budgeted ledger against an actual ledger and produces a variance report. Both inputs are dictionaries mapping account names (strings) to amounts in cents (integers). The report must be a dictionary mapping each account name appearing in either ledger to a tuple `(variance_cents, variance_pct)` where variance is `actual - budget` (positive means over budget). The percentage is computed as `Decimal(variance) / Decimal(budget) * 100` rounded to 2 decimal places with ROUND_HALF_UP, and is `None` when budget is 0 (regardless of actual). Include every account that appears in either input; missing amounts are treated as 0. Example: budget = {'office_supplies': 5000, 'rent': 120000}, actual = {'office_supplies': 4500, 'rent': 120000, 'utilities': 8000} yields {'office_supplies': (-500, Decimal('-10.00')), 'rent': (0, Decimal('0.00')), 'utilities': (8000, None)}. Use the `decimal` module for the percentage calculation."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef variance_report(budget, actual):\n \"\"\"Compare budget vs actual ledgers (amounts in cents).\n\n Returns {account: (variance_cents, variance_pct_or_None)}.\n variance_pct is None when the budget for that account is 0.\n \"\"\"\n accounts = set(budget) | set(actual)\n report = {}\n for account in sorted(accounts):\n b = budget.get(account, 0)\n a = actual.get(account, 0)\n variance = a - b\n if b == 0:\n pct = None\n else:\n pct = (Decimal(variance) / Decimal(b) * 100).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP\n )\n report[account] = (variance, pct)\n return report\n\n\nif __name__ == '__main__':\n budget = {'office_supplies': 5000, 'rent': 120000}\n actual = {'office_supplies': 4500, 'rent': 120000, 'utilities': 8000}\n result = variance_report(budget, actual)\n print(result)\n expected = {\n 'office_supplies': (-500, Decimal('-10.00')),\n 'rent': (0, Decimal('0.00')),\n 'utilities': (8000, None),\n }\n assert result == expected, result\n print('All checks passed.')"}], "meta": {"idx": 2434, "topic": "budget versus actual variance analysis", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 556, "latency_s": 187.1}} +{"prompt": [{"role": "user", "content": "Define a dataclass `JournalEntry` representing a bookkeeping journal entry with fields: `date` (string, ISO format YYYY-MM-DD), `description` (string), `debit_account` (string), `credit_account` (string), and `amount` (a `decimal.Decimal` rounded to 2 decimal places using ROUND_HALF_UP). Then write a function `validate_entries(entries)` that takes a list of `JournalEntry` objects and returns a list of booleans, where each entry is valid if: the date matches the pattern YYYY-MM-DD and represents a real calendar date, the amount is strictly greater than zero, and both account names are non-empty strings. Finally, write a function `total_amount(entries)` that returns the sum of the `amount` fields of all entries as a Decimal rounded to 2 decimal places. Example: an entry with date '2024-02-30' is invalid (not a real date), an entry with date '2024-02-29' is valid (2024 is a leap year), and an entry with amount Decimal('0') is invalid. For instance, given entries [('2024-03-01','Rent paid','Cash','Rent Expense',Decimal('1200.005')) and ('2023-02-29','Bad date','A','B',Decimal('10'))], the first entry's amount becomes Decimal('1200.01') and is valid, while the second is invalid; total_amount returns Decimal('1200.01') since only valid amounts... actually total_amount sums ALL entries, so it returns Decimal('1210.01')."}], "completion": [{"role": "assistant", "content": "import re\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom decimal import Decimal, ROUND_HALF_UP\n\nTWO_PLACES = Decimal('0.01')\n\n@dataclass\nclass JournalEntry:\n date: str\n description: str\n debit_account: str\n credit_account: str\n amount: Decimal\n\n def __post_init__(self):\n if not isinstance(self.amount, Decimal):\n self.amount = Decimal(str(self.amount))\n self.amount = self.amount.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\ndef _is_real_date(date_str):\n if not isinstance(date_str, str) or not re.fullmatch(r'\\d{4}-\\d{2}-\\d{2}', date_str):\n return False\n try:\n datetime.strptime(date_str, '%Y-%m-%d')\n return True\n except ValueError:\n return False\n\ndef validate_entries(entries):\n results = []\n for e in entries:\n valid = (\n _is_real_date(e.date)\n and isinstance(e.amount, Decimal)\n and e.amount > Decimal('0')\n and isinstance(e.debit_account, str) and e.debit_account.strip() != ''\n and isinstance(e.credit_account, str) and e.credit_account.strip() != ''\n )\n results.append(valid)\n return results\n\ndef total_amount(entries):\n total = sum((e.amount for e in entries), Decimal('0'))\n return total.quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n\nif __name__ == '__main__':\n entries = [\n JournalEntry('2024-03-01', 'Rent paid', 'Rent Expense', 'Cash', Decimal('1200.005')),\n JournalEntry('2023-02-29', 'Bad date', 'A', 'B', Decimal('10')),\n JournalEntry('2024-02-29', 'Leap day', 'A', 'B', Decimal('5.50')),\n JournalEntry('2024-01-15', 'Zero amount', 'A', 'B', Decimal('0')),\n ]\n print(validate_entries(entries)) # [True, False, True, False]\n print(total_amount(entries)) # 1215.51\n assert validate_entries(entries) == [True, False, True, False]\n assert total_amount(entries) == Decimal('1215.51')\n assert entries[0].amount == Decimal('1200.01')"}], "meta": {"idx": 2441, "topic": "accounting record dataclasses and schemas", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 854, "latency_s": 95.2}} +{"prompt": [{"role": "user", "content": "You are given a list of bookkeeping entries, where each entry is a tuple (date, description, amount). The amount is a Decimal representing a debit (positive) or credit (negative) in cents-scaled currency (e.g., Decimal('12.34')). An entry is considered a duplicate if another entry with the exact same date, description, and amount appears anywhere in the list. An entry is considered anomalous if its absolute amount is greater than or equal to 1000.00. Write a function flag_entries(entries) that returns a list of strings, one per input entry in the same order: 'DUPLICATE' if the entry appears more than once in the list (regardless of anomaly), 'ANOMALY' if it is not a duplicate but its absolute amount is >= 1000.00, and 'OK' otherwise. Use Decimal for all monetary comparisons with no rounding. For example, flag_entries([('2024-01-05', 'Office supplies', Decimal('125.00')), ('2024-01-05', 'Office supplies', Decimal('125.00')), ('2024-01-06', 'Consulting fee', Decimal('2500.00')), ('2024-01-07', 'Coffee', Decimal('8.50'))]) returns ['DUPLICATE', 'DUPLICATE', 'ANOMALY', 'OK']. The input may contain up to 100,000 entries, so avoid quadratic behavior."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom collections import Counter\n\n\ndef flag_entries(entries):\n counts = Counter(entries)\n flags = []\n for entry in entries:\n if counts[entry] > 1:\n flags.append('DUPLICATE')\n elif abs(entry[2]) >= Decimal('1000.00'):\n flags.append('ANOMALY')\n else:\n flags.append('OK')\n return flags\n\n\nif __name__ == '__main__':\n sample = [\n ('2024-01-05', 'Office supplies', Decimal('125.00')),\n ('2024-01-05', 'Office supplies', Decimal('125.00')),\n ('2024-01-06', 'Consulting fee', Decimal('2500.00')),\n ('2024-01-07', 'Coffee', Decimal('8.50')),\n ]\n print(flag_entries(sample))\n # Expected: ['DUPLICATE', 'DUPLICATE', 'ANOMALY', 'OK']"}], "meta": {"idx": 2457, "topic": "detecting duplicate or anomalous transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 494, "latency_s": 5.2}} +{"prompt": [{"role": "user", "content": "Implement a small double-entry journal module using only the standard library. Define a frozen dataclass Line(account, debit, credit) whose Decimal amounts are quantized to cents with ROUND_HALF_EVEN, where exactly one of debit/credit must be strictly positive, and a frozen dataclass JournalEntry(entry_id, date, description, lines) that requires a non-empty entry_id, a valid ISO date string, at least two lines, and total debits exactly equal to total credits; any violation raises LedgerError. Implement a Ledger class with a fixed chart of accounts, an atomic post(entry) method (rejecting unknown accounts and duplicate entry_ids without mutating state), account_balance(account) that returns the net balance with debits counted positive, trial_balance() returning (per-account balance dict, balanced_flag), and a static allocate(amount, weights) that splits a cent-quantized amount into len(weights) cent-quantized parts proportional to non-negative weights, with the final part absorbing the rounding residual so the parts sum exactly to amount. For example, allocate(Decimal('100.00'), [1, 1, 1]) must return (Decimal('33.33'), Decimal('33.33'), Decimal('33.34')), and posting lines (account '1010', debit 100.00) and (account '4000', credit 100.00) to a ledger with accounts {'1010', '4000'} must give account_balance('1010') == Decimal('100.00'), account_balance('4000') == Decimal('-100.00'), and a balanced trial balance. All monetary values produced by the module must be Decimal objects quantized to exactly two decimal places."}], "completion": [{"role": "assistant", "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_EVEN\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\nclass LedgerError(Exception):\n \"\"\"Raised for any schema, balance, or posting violation.\"\"\"\n\n\ndef to_cents(value) -> Decimal:\n \"\"\"Convert a value to a Decimal quantized to cents (banker's rounding).\"\"\"\n if not isinstance(value, Decimal):\n try:\n value = Decimal(str(value))\n except Exception as exc:\n raise LedgerError(f\"invalid monetary value {value!r}\") from exc\n if not value.is_finite():\n raise LedgerError(f\"non-finite monetary value {value!r}\")\n return value.quantize(CENT, rounding=ROUND_HALF_EVEN)\n\n\n@dataclass(frozen=True)\nclass Line:\n \"\"\"A single journal line: exactly one of debit/credit is positive.\"\"\"\n\n account: str\n debit: Decimal = ZERO\n credit: Decimal = ZERO\n\n def __post_init__(self) -> None:\n object.__setattr__(self, \"debit\", to_cents(self.debit))\n object.__setattr__(self, \"credit\", to_cents(self.credit))\n if self.debit < ZERO or self.credit < ZERO:\n raise LedgerError(f\"negative amount on account {self.account!r}\")\n if (self.debit > ZERO) == (self.credit > ZERO):\n raise LedgerError(\n f\"line for account {self.account!r} must have exactly \"\n f\"one strictly positive side (debit={self.debit}, credit={self.credit})\"\n )\n\n @property\n def signed(self) -> Decimal:\n \"\"\"Net effect on an account balance: debit-positive.\"\"\"\n return self.debit - self.credit\n\n\n@dataclass(frozen=True)\nclass JournalEntry:\n \"\"\"A balanced, immutable journal entry.\"\"\"\n\n entry_id: str\n date: str\n description: str\n lines: tuple\n\n def __post_init__(self) -> None:\n if not isinstance(self.entry_id, str) or not self.entry_id:\n raise LedgerError(\"entry_id must be a non-empty string\")\n if not isinstance(self.date, str):\n raise LedgerError(\"date must be an ISO-format string\")\n try:\n date.fromisoformat(self.date)\n except ValueError as exc:\n raise LedgerError(f\"invalid ISO date {self.date!r}\") from exc\n object.__setattr__(self, \"lines\", tuple(self.lines))\n for line in self.lines:\n if not isinstance(line, Line):\n raise LedgerError(f\"line {line!r} is not a Line instance\")\n if len(self.lines) < 2:\n raise LedgerError(\"entry must contain at least two lines\")\n debits = sum((line.debit for line in self.lines), ZERO)\n credits = sum((line.credit for line in self.lines), ZERO)\n if debits != credits:\n raise LedgerError(\n f\"unbalanced entry {self.entry_id!r}: \"\n f\"debits {debits} != credits {credits}\"\n )\n\n @property\n def total(self) -> Decimal:\n return sum((line.debit for line in self.lines), ZERO)\n\n\nclass Ledger:\n \"\"\"A simple ledger over a fixed chart of accounts.\"\"\"\n\n def __init__(self, accounts) -> None:\n self._accounts = set(accounts)\n if not self._accounts:\n raise LedgerError(\"chart of accounts must be non-empty\")\n self._entries = {}\n self._balances = {account: ZERO for account in self._accounts}\n\n def post(self, entry: JournalEntry) -> None:\n \"\"\"Atomically post a validated entry; reject unknown/duplicate ids.\"\"\"\n if not isinstance(entry, JournalEntry):\n raise LedgerError(f\"{entry!r} is not a JournalEntry\")\n for line in entry.lines:\n if line.account not in self._accounts:\n raise LedgerError(f\"unknown account {line.account!r}\")\n if entry.entry_id in self._entries:\n raise LedgerError(f\"duplicate entry_id {entry.entry_id!r}\")\n for line in entry.lines:\n self._balances[line.account] += line.signed\n self._entries[entry.entry_id] = entry\n\n def account_balance(self, account: str) -> Decimal:\n if account not in self._accounts:\n raise LedgerError(f\"unknown account {account!r}\")\n return self._balances[account]\n\n def trial_balance(self):\n \"\"\"Return (per-account balances, balanced_flag).\"\"\"\n balances = dict(self._balances)\n total = sum(balances.values(), ZERO)\n return balances, total == ZERO\n\n @staticmethod\n def allocate(amount, weights):\n \"\"\"Split a cent-quantized amount proportionally across weights.\n\n Every part is quantized to cents with ROUND_HALF_EVEN; the final\n part absorbs the rounding residual so parts sum exactly to amount.\n \"\"\"\n amount = to_cents(amount)\n if amount < ZERO:\n raise LedgerError(\"amount to allocate must be non-negative\")\n try:\n w = [Decimal(str(x)) for x in weights]\n except Exception as exc:\n raise LedgerError(f\"invalid weights {weights!r}\") from exc\n if not w:\n raise LedgerError(\"weights must be non-empty\")\n if any(x < 0 for x in w):\n raise LedgerError(\"weights must be non-negative\")\n total_weight = sum(w, Decimal(0))\n if total_weight <= 0:\n raise LedgerError(\"total weight must be strictly positive\")\n parts = []\n running = ZERO\n for weight in w[:-1]:\n share = to_cents(amount * weight / total_weight)\n parts.append(share)\n running += share\n parts.append((amount - running).quantize(CENT, rounding=ROUND_HALF_EVEN))\n return tuple(parts)\n\n\nif __name__ == \"__main__\":\n # Worked example: proportional allocation with residual absorption.\n parts = Ledger.allocate(Decimal(\"100.00\"), [1, 1, 1])\n assert parts == (Decimal(\"33.33\"), Decimal(\"33.33\"), Decimal(\"33.34\"))\n assert sum(parts, ZERO) == Decimal(\"100.00\")\n\n # Worked example: posting a balanced entry and reading the trial balance.\n ledger = Ledger([\"1010\", \"4000\"])\n entry = JournalEntry(\n entry_id=\"JE-0001\",\n date=\"2024-06-30\",\n description=\"Cash sale\",\n lines=(\n Line(account=\"1010\", debit=Decimal(\"100.00\")),\n Line(account=\"4000\", credit=Decimal(\"100.00\")),\n ),\n )\n ledger.post(entry)\n assert ledger.account_balance(\"1010\") == Decimal(\"100.00\")\n assert ledger.account_balance(\"4000\") == Decimal(\"-100.00\")\n balances, balanced = ledger.trial_balance()\n assert balanced is True\n assert balances == {\"1010\": Decimal(\"100.00\"), \"4000\": Decimal(\"-100.00\")}\n\n # Violations raise LedgerError.\n for bad_call in (\n lambda: JournalEntry(\"JE-0002\", \"2024-06-30\", \"bad\", (\n Line(\"1010\", debit=Decimal(\"10.00\")),\n )),\n lambda: JournalEntry(\"JE-0003\", \"2024-06-30\", \"unbalanced\", (\n Line(\"1010\", debit=Decimal(\"10.00\")),\n Line(\"4000\", credit=Decimal(\"9.99\")),\n )),\n lambda: ledger.post(JournalEntry(\"JE-0004\", \"2024-06-30\", \"unknown acct\", (\n Line(\"9999\", debit=Decimal(\"5.00\")),\n Line(\"4000\", credit=Decimal(\"5.00\")),\n ))),\n lambda: ledger.post(entry), # duplicate entry_id\n lambda: Ledger.allocate(Decimal(\"10.00\"), [0, 0]),\n ):\n try:\n bad_call()\n except LedgerError:\n pass\n else:\n raise AssertionError(\"expected LedgerError\")\n\n # Ledger state must be unchanged after the failed posts above.\n balances, balanced = ledger.trial_balance()\n assert balances == {\"1010\": Decimal(\"100.00\"), \"4000\": Decimal(\"-100.00\")}\n assert balanced is True\n\n print(\"all accounting checks passed\")\n print(\"allocate(100.00, [1,1,1]) ->\", parts)\n print(\"trial balance ->\", balances, \"balanced:\", balanced)"}], "meta": {"idx": 2426, "topic": "accounting record dataclasses and schemas", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2453, "latency_s": 229.5}} +{"prompt": [{"role": "user", "content": "Write a function reconcile(book_start_balance, bank_start_balance, ledger_entries, bank_lines, tolerance_days=3) that reconciles a company's book (ledger) records against a bank statement, using only the standard library. Inputs: book_start_balance and bank_start_balance are Decimal-parseable strings for the balances before any listed activity; ledger_entries and bank_lines are lists of (ISO-date-string, description, amount-string) tuples where a positive amount means money into the account (ledger amounts may carry sub-cent precision, bank lines are exact cents). A ledger entry matches a bank line if the entry's amount quantized to cents with Decimal ROUND_HALF_UP equals the line's amount AND the dates differ by at most tolerance_days; process bank lines in ascending date order and match each to the earliest-dated still-unmatched eligible ledger entry, strictly one-to-one. Unmatched bank lines become bank_only items (fees/interest) and unmatched ledger entries become book_only items (outstanding checks when negative, deposits in transit when positive). Compute adjusted_book_balance = book balance + sum of bank_only amounts and adjusted_bank_balance = bank balance + sum of book_only amounts; the reconciliation succeeds (reconciled = True) when adjusted_bank_balance equals adjusted_book_balance quantized to cents with ROUND_HALF_UP, and difference = adjusted_bank_balance - adjusted_book_balance. Return a dict with keys matched (list of pair dicts), bank_only, book_only, adjusted_book_balance, adjusted_bank_balance, difference, reconciled. Worked example: book_start = \"1000.00\", bank_start = \"1000.00\", ledger = [(\"2024-06-01\",\"Client payment INV-204\",\"250.50\"), (\"2024-06-02\",\"Check #1183 rent\",\"-400.00\"), (\"2024-06-03\",\"Deposit cash sales\",\"150.004\"), (\"2024-06-05\",\"Deposit in transit\",\"300.00\")], bank = [(\"2024-06-02\",\"CLIENT PYMT INV-204\",\"250.50\"), (\"2024-06-04\",\"DEPOSIT CASH SALES\",\"150.00\"), (\"2024-06-05\",\"MONTHLY MAINT FEE\",\"-12.50\"), (\"2024-06-06\",\"INTEREST CREDIT\",\"1.25\")]. Expected: 2 matched pairs (INV-204 250.50 dated 06-01/06-02; cash sales 150.004 rounded to 150.00 dated 06-03/06-04), bank_only = fee -12.50 and interest 1.25, book_only = check -400.00 and deposit-in-transit 300.00, adjusted_book_balance = Decimal('1289.254'), adjusted_bank_balance = Decimal('1289.25'), difference = Decimal('-0.004'), reconciled = True."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nCENT = Decimal(\"0.01\")\n\n\ndef _to_cents(amount):\n return amount.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef reconcile(book_start_balance, bank_start_balance, ledger_entries, bank_lines,\n tolerance_days=3):\n book_bal = Decimal(book_start_balance)\n bank_bal = Decimal(bank_start_balance)\n\n ledger = [\n {\"idx\": i, \"date\": date.fromisoformat(d), \"desc\": desc, \"amount\": Decimal(amt)}\n for i, (d, desc, amt) in enumerate(ledger_entries)\n ]\n bank = [\n {\"idx\": i, \"date\": date.fromisoformat(d), \"desc\": desc, \"amount\": Decimal(amt)}\n for i, (d, desc, amt) in enumerate(bank_lines)\n ]\n\n used_ledger = set()\n matched_bank = set()\n matched = []\n\n # Process bank lines in date order (ties broken by input order).\n for s in sorted(bank, key=lambda x: (x[\"date\"], x[\"idx\"])):\n candidates = [\n l for l in ledger\n if l[\"idx\"] not in used_ledger\n and _to_cents(l[\"amount\"]) == s[\"amount\"]\n and abs((l[\"date\"] - s[\"date\"]).days) <= tolerance_days\n ]\n if candidates:\n l = min(candidates, key=lambda x: (x[\"date\"], x[\"idx\"]))\n used_ledger.add(l[\"idx\"])\n matched_bank.add(s[\"idx\"])\n matched.append({\n \"ledger_date\": l[\"date\"].isoformat(),\n \"ledger_desc\": l[\"desc\"],\n \"ledger_amount\": str(l[\"amount\"]),\n \"bank_date\": s[\"date\"].isoformat(),\n \"bank_desc\": s[\"desc\"],\n \"bank_amount\": str(s[\"amount\"]),\n })\n\n bank_only = [\n {\"date\": s[\"date\"].isoformat(), \"desc\": s[\"desc\"], \"amount\": s[\"amount\"]}\n for s in bank if s[\"idx\"] not in matched_bank\n ]\n book_only = [\n {\"date\": l[\"date\"].isoformat(), \"desc\": l[\"desc\"], \"amount\": l[\"amount\"]}\n for l in ledger if l[\"idx\"] not in used_ledger\n ]\n\n adjusted_book = book_bal + sum((item[\"amount\"] for item in bank_only), Decimal(\"0\"))\n adjusted_bank = bank_bal + sum((item[\"amount\"] for item in book_only), Decimal(\"0\"))\n difference = adjusted_bank - adjusted_book\n reconciled = _to_cents(adjusted_book) == _to_cents(adjusted_bank)\n\n return {\n \"matched\": matched,\n \"bank_only\": bank_only,\n \"book_only\": book_only,\n \"adjusted_book_balance\": adjusted_book,\n \"adjusted_bank_balance\": adjusted_bank,\n \"difference\": difference,\n \"reconciled\": reconciled,\n }\n\n\ndef main():\n book_start = \"1000.00\"\n bank_start = \"1000.00\"\n ledger = [\n (\"2024-06-01\", \"Client payment INV-204\", \"250.50\"),\n (\"2024-06-02\", \"Check #1183 rent\", \"-400.00\"),\n (\"2024-06-03\", \"Deposit cash sales\", \"150.004\"),\n (\"2024-06-05\", \"Deposit in transit\", \"300.00\"),\n ]\n bank = [\n (\"2024-06-02\", \"CLIENT PYMT INV-204\", \"250.50\"),\n (\"2024-06-04\", \"DEPOSIT CASH SALES\", \"150.00\"),\n (\"2024-06-05\", \"MONTHLY MAINT FEE\", \"-12.50\"),\n (\"2024-06-06\", \"INTEREST CREDIT\", \"1.25\"),\n ]\n\n result = reconcile(book_start, bank_start, ledger, bank)\n\n print(\"Matched pairs:\")\n for m in result[\"matched\"]:\n print(\" ledger {ledger_date} {ledger_desc} {ledger_amount} \"\n \"<-> bank {bank_date} {bank_desc} {bank_amount}\".format(**m))\n print(\"Bank-only items (fees/interest):\")\n for item in result[\"bank_only\"]:\n print(\" {date} {desc} {amount}\".format(**item))\n print(\"Book-only items (outstanding checks / deposits in transit):\")\n for item in result[\"book_only\"]:\n print(\" {date} {desc} {amount}\".format(**item))\n print(\"Adjusted book balance:\", result[\"adjusted_book_balance\"])\n print(\"Adjusted bank balance:\", result[\"adjusted_bank_balance\"])\n print(\"Difference:\", result[\"difference\"])\n print(\"Reconciled:\", result[\"reconciled\"])\n\n assert len(result[\"matched\"]) == 2\n assert result[\"bank_only\"] == [\n {\"date\": \"2024-06-05\", \"desc\": \"MONTHLY MAINT FEE\", \"amount\": Decimal(\"-12.50\")},\n {\"date\": \"2024-06-06\", \"desc\": \"INTEREST CREDIT\", \"amount\": Decimal(\"1.25\")},\n ]\n assert result[\"book_only\"] == [\n {\"date\": \"2024-06-02\", \"desc\": \"Check #1183 rent\", \"amount\": Decimal(\"-400.00\")},\n {\"date\": \"2024-06-05\", \"desc\": \"Deposit in transit\", \"amount\": Decimal(\"300.00\")},\n ]\n assert result[\"adjusted_book_balance\"] == Decimal(\"1289.254\")\n assert result[\"adjusted_bank_balance\"] == Decimal(\"1289.25\")\n assert result[\"difference\"] == Decimal(\"-0.004\")\n assert result[\"reconciled\"] is True\n print(\"All assertions passed.\")\n\n\nif __name__ == \"__main__\":\n main()"}], "meta": {"idx": 2448, "topic": "bank statement reconciliation", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1887, "latency_s": 63.5}} +{"prompt": [{"role": "user", "content": "Write a program that reads a CSV file of bank transactions (columns: date, description, amount, currency), validates each row, and exports a cleaned ledger. A row is valid if: the date matches YYYY-MM-DD and is parseable, the amount is a decimal number with at most 2 decimal places (no rounding allowed \u2014 reject rows with more precision), and the currency is one of USD, EUR, GBP. Invalid rows should be written to a rejects file with a reason column. Valid rows must be sorted by date, amounts stored as Decimal, and the exported CSV must show amounts formatted to exactly 2 decimal places. Finally, print a summary line: 'Imported N transactions, total USD: X' where X is the sum of USD amounts rounded half-up to 2 decimals (other currencies are imported but excluded from the total). Example input row: '2024-01-15,Office supplies,-45.50,USD' is valid; '2024-13-01,Bad date,10.00,USD' is invalid because month 13 is not parseable; '2024-01-15,Too precise,10.123,USD' is invalid because it has 3 decimal places."}], "completion": [{"role": "assistant", "content": "import csv\nimport sys\nfrom datetime import datetime\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCURRENCIES = {\"USD\", \"EUR\", \"GBP\"}\n\n\ndef validate_date(value):\n try:\n datetime.strptime(value, \"%Y-%m-%d\")\n return True, \"\"\n except ValueError:\n return False, \"invalid date\"\n\n\ndef validate_amount(value):\n try:\n d = Decimal(value)\n except Exception:\n return False, None, \"invalid amount\"\n if not d.is_finite():\n return False, None, \"invalid amount\"\n exponent = d.as_tuple().exponent\n if exponent < -2:\n return False, None, \"too many decimal places\"\n return True, d, \"\"\n\n\ndef process(input_path, output_path, rejects_path):\n valid_rows = []\n rejected = []\n with open(input_path, newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n for i, row in enumerate(reader):\n if i == 0 and row and row[0].strip().lower() == \"date\":\n continue\n if len(row) != 4:\n rejected.append(row + [\"wrong column count\"])\n continue\n date, desc, amount, currency = (c.strip() for c in row)\n reasons = []\n ok_date, reason = validate_date(date)\n if not ok_date:\n reasons.append(reason)\n ok_amount, amt, reason = validate_amount(amount)\n if not ok_amount:\n reasons.append(reason)\n if currency not in CURRENCIES:\n reasons.append(\"unknown currency\")\n if reasons:\n rejected.append([date, desc, amount, currency, \"; \".join(reasons)])\n else:\n valid_rows.append((date, desc, amt, currency))\n\n valid_rows.sort(key=lambda r: r[0])\n\n with open(output_path, \"w\", newline=\"\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n writer.writerow([\"date\", \"description\", \"amount\", \"currency\"])\n for date, desc, amt, cur in valid_rows:\n writer.writerow([date, desc, f\"{amt:.2f}\", cur])\n\n with open(rejects_path, \"w\", newline=\"\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n writer.writerow([\"date\", \"description\", \"amount\", \"currency\", \"reason\"])\n writer.writerows(rejected)\n\n usd_total = sum((amt for _, _, amt, cur in valid_rows if cur == \"USD\"), Decimal(\"0\"))\n usd_total = usd_total.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_UP)\n print(f\"Imported {len(valid_rows)} transactions, total USD: {usd_total}\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 4:\n print(\"Usage: python ledger_import.py input.csv ledger.csv rejects.csv\", file=sys.stderr)\n sys.exit(1)\n process(sys.argv[1], sys.argv[2], sys.argv[3])"}], "meta": {"idx": 2454, "topic": "transaction CSV import, validation, and export", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 977, "latency_s": 63.9}} +{"prompt": [{"role": "user", "content": "You are auditing a company ledger to flag suspicious entries. Each transaction is a tuple (txn_id, date, counterparty, amount), where date is a string 'YYYY-MM-DD' and amount is a decimal string (negative for outgoing payments). Classify each transaction, processing the list in order, with these rules checked in strict priority: (1) 'DUPLICATE' if some earlier transaction in the list has the same date, the same counterparty, and an identical amount (compared as Decimal amounts quantized to cents with ROUND_HALF_UP); (2) 'TRANSPOSITION' if no duplicate exists, but some earlier transaction on the same date with the same counterparty has an amount whose value in integer cents (sign preserved, absolute value zero-padded to equal digit length) becomes this transaction's cents value after swapping exactly one pair of adjacent digits; (3) 'ANOMALOUS' if adding this amount to the running balance (starting balance plus the sum of all amounts classified VALID so far) would make the balance negative; (4) otherwise 'VALID', and the amount is added to the running balance. Return a list of (txn_id, classification) pairs plus the final balance, where the final balance is the starting balance plus the sum of all VALID amounts, expressed as a Decimal quantized to cents; all monetary arithmetic must use Decimal with ROUND_HALF_UP. Worked example: starting balance '5000.00' with transactions [('T001','2024-01-02','Acme Corp','-1250.00'), ('T002','2024-01-02','Acme Corp','-1250.00'), ('T003','2024-01-05','Globex','89.12'), ('T004','2024-01-05','Globex','98.12'), ('T005','2024-01-06','Initech','500.00'), ('T006','2024-01-06','Initech','500.00'), ('T007','2024-01-08','Umbrella','-10000.00')] yields [('T001','VALID'), ('T002','DUPLICATE'), ('T003','VALID'), ('T004','TRANSPOSITION'), ('T005','VALID'), ('T006','DUPLICATE'), ('T007','ANOMALOUS')] and a final balance of Decimal('4339.12'), because 8912 cents and 9812 cents differ by one adjacent-digit swap and the -10000.00 payment would overdraw the 4339.12 balance."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nCENT = Decimal(\"0.01\")\n\n\ndef _to_cents(amount: Decimal) -> int:\n \"\"\"Convert a cent-quantized Decimal amount to an integer number of minor units.\"\"\"\n return int(amount * 100)\n\n\ndef _is_transposition(a_cents: int, b_cents: int) -> bool:\n \"\"\"True if the digit strings of |a_cents| and |b_cents| (zero-padded to the\n same length) differ by exactly one swap of adjacent digits. Signs must match.\"\"\"\n if (a_cents < 0) != (b_cents < 0):\n return False\n sa = str(abs(a_cents))\n sb = str(abs(b_cents))\n n = max(len(sa), len(sb))\n sa = sa.zfill(n)\n sb = sb.zfill(n)\n if sa == sb:\n return False\n for i in range(n - 1):\n if sa[i] == sa[i + 1]:\n continue\n chars = list(sa)\n chars[i], chars[i + 1] = chars[i + 1], chars[i]\n if \"\".join(chars) == sb:\n return True\n return False\n\n\ndef audit_ledger(starting_balance, transactions):\n \"\"\"Classify ledger transactions and compute the cleaned final balance.\n\n Returns (classifications, final_balance) where classifications is a list\n of (txn_id, label) pairs with label in {'DUPLICATE','TRANSPOSITION',\n 'ANOMALOUS','VALID'} and final_balance is a Decimal quantized to cents.\n \"\"\"\n balance = Decimal(str(starting_balance)).quantize(CENT, rounding=ROUND_HALF_UP)\n history = [] # (date, counterparty, amount Decimal, cents int)\n classifications = []\n\n for txn_id, date_str, counterparty, amount_str in transactions:\n amt = Decimal(str(amount_str)).quantize(CENT, rounding=ROUND_HALF_UP)\n cents = _to_cents(amt)\n txn_date = date.fromisoformat(date_str)\n\n if any(\n h_date == txn_date and h_cp == counterparty and h_amt == amt\n for h_date, h_cp, h_amt, _ in history\n ):\n label = \"DUPLICATE\"\n elif any(\n h_date == txn_date\n and h_cp == counterparty\n and _is_transposition(h_cents, cents)\n for h_date, h_cp, _, h_cents in history\n ):\n label = \"TRANSPOSITION\"\n elif balance + amt < 0:\n label = \"ANOMALOUS\"\n else:\n label = \"VALID\"\n\n if label == \"VALID\":\n balance = (balance + amt).quantize(CENT, rounding=ROUND_HALF_UP)\n\n classifications.append((txn_id, label))\n history.append((txn_date, counterparty, amt, cents))\n\n return classifications, balance\n\n\nif __name__ == \"__main__\":\n starting_balance = \"5000.00\"\n transactions = [\n (\"T001\", \"2024-01-02\", \"Acme Corp\", \"-1250.00\"),\n (\"T002\", \"2024-01-02\", \"Acme Corp\", \"-1250.00\"),\n (\"T003\", \"2024-01-05\", \"Globex\", \"89.12\"),\n (\"T004\", \"2024-01-05\", \"Globex\", \"98.12\"),\n (\"T005\", \"2024-01-06\", \"Initech\", \"500.00\"),\n (\"T006\", \"2024-01-06\", \"Initech\", \"500.00\"),\n (\"T007\", \"2024-01-08\", \"Umbrella\", \"-10000.00\"),\n ]\n labels, final_balance = audit_ledger(starting_balance, transactions)\n expected_labels = [\n (\"T001\", \"VALID\"),\n (\"T002\", \"DUPLICATE\"),\n (\"T003\", \"VALID\"),\n (\"T004\", \"TRANSPOSITION\"),\n (\"T005\", \"VALID\"),\n (\"T006\", \"DUPLICATE\"),\n (\"T007\", \"ANOMALOUS\"),\n ]\n assert labels == expected_labels, labels\n assert final_balance == Decimal(\"4339.12\"), final_balance\n for txn_id, label in labels:\n print(f\"{txn_id}: {label}\")\n print(f\"Final balance: {final_balance}\")"}], "meta": {"idx": 2459, "topic": "detecting duplicate or anomalous transactions", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1441, "latency_s": 41.7}} +{"prompt": [{"role": "user", "content": "You are maintaining a simple ledger of bookkeeping entries. Each entry is a tuple (date, description, amount) where amount is a Decimal string; positive amounts are debits and negative amounts are credits. Write a function `net_balance(entries)` that returns the net balance (sum of all amounts) as a Decimal, rounded to 2 decimal places using ROUND_HALF_UP. Then write a function `apply_corrections(entries, corrections)` where corrections is a list of tuples (index, new_amount): each correction replaces the amount of the entry at the given index (0-based) with new_amount (a Decimal string); a new_amount of exactly '0.00' means the entry is voided and should contribute nothing to the balance, but the entry still remains in the list. Return the net balance after applying all corrections. For example, entries = [('2024-01-01','sale','100.00'), ('2024-01-02','refund','-30.00'), ('2024-01-03','fee','5.50')] gives net_balance = Decimal('75.50'); if corrections = [(1,'0.00'), (2,'2.25')] the refund is voided and the fee is restated, giving a final balance of Decimal('102.25'). Your functions must use the decimal module with ROUND_HALF_UP rounding and handle invalid indices by ignoring that correction."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef net_balance(entries):\n total = sum((Decimal(amount) for _, _, amount in entries), Decimal('0.00'))\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef apply_corrections(entries, corrections):\n corrected = [list(e) for e in entries]\n for index, new_amount in corrections:\n if 0 <= index < len(corrected):\n corrected[index][2] = new_amount\n total = Decimal('0.00')\n for _, _, amount in corrected:\n value = Decimal(amount)\n if value == Decimal('0.00'):\n continue\n total += value\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n entries = [\n ('2024-01-01', 'sale', '100.00'),\n ('2024-01-02', 'refund', '-30.00'),\n ('2024-01-03', 'fee', '5.50'),\n ]\n print(net_balance(entries)) # 75.50\n print(apply_corrections(entries, [(1, '0.00'), (2, '2.25')])) # 102.25\n print(apply_corrections(entries, [(99, '1.00')])) # invalid index ignored: 75.50"}], "meta": {"idx": 2462, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 582, "latency_s": 9.2}} +{"prompt": [{"role": "user", "content": "You are given a small business's monthly budget and actual spending as a list of (category, budgeted_amount, actual_amount) tuples, where amounts are strings representing dollars and cents. Write a function `variance_report(entries)` that returns a list of tuples (category, variance) where variance = budgeted \u2212 actual, computed exactly using `decimal.Decimal` and rounded to 2 decimal places with ROUND_HALF_UP. A positive variance means under budget (favorable); a negative variance means over budget (unfavorable). Then include in the returned list, as the final tuple, a category named 'TOTAL' with the sum of all variances, rounded the same way. For example, given [('Office Supplies', '150.00', '142.35'), ('Rent', '1200.00', '1250.00')], the result is [('Office Supplies', Decimal('7.65')), ('Rent', Decimal('-50.00')), ('TOTAL', Decimal('-42.35'))]. The function must not modify the input and must handle an empty list by returning [('TOTAL', Decimal('0.00'))]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef _round2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef variance_report(entries):\n \"\"\"Compute budget vs actual variances per category plus a TOTAL row.\n\n Args:\n entries: iterable of (category, budgeted_amount, actual_amount) where\n amounts are strings of dollars and cents.\n\n Returns:\n List of (category, Decimal variance) tuples, ending with the TOTAL row.\n Variance = budgeted - actual, rounded to 2 places with ROUND_HALF_UP.\n \"\"\"\n results = []\n total = Decimal('0')\n for category, budget_str, actual_str in entries:\n budget = Decimal(budget_str)\n actual = Decimal(actual_str)\n variance = _round2(budget - actual)\n results.append((category, variance))\n total += variance\n results.append(('TOTAL', _round2(total)))\n return results\n\n\nif __name__ == '__main__':\n example = [('Office Supplies', '150.00', '142.35'),\n ('Rent', '1200.00', '1250.00')]\n result = variance_report(example)\n print(result)\n assert result == [('Office Supplies', Decimal('7.65')),\n ('Rent', Decimal('-50.00')),\n ('TOTAL', Decimal('-42.35'))]\n assert variance_report([]) == [('TOTAL', Decimal('0.00'))]\n print('All checks passed.')"}], "meta": {"idx": 2463, "topic": "budget versus actual variance analysis", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 602, "latency_s": 5.0}} +{"prompt": [{"role": "user", "content": "You are given a double-entry general ledger as a list of journal entries; each entry is a list of (account, side, amount) tuples, where side is 'debit' or 'credit' and amount is a string like '250.50'. Accounts are named with a category prefix: 'Asset:...', 'Liability:...', 'Equity:...', 'Revenue:...', or 'Expense:...'. Write a function summarize(entries) that first validates every entry (the sum of its debits must equal the sum of its credits, otherwise raise ValueError with the 1-based entry number), then posts all entries using Decimal arithmetic with amounts quantized to cents via ROUND_HALF_UP, and finally returns a report dictionary containing: the net balance of every account (debit-normal for Asset/Expense accounts, credit-normal for the rest), total assets, total liabilities, total equity, total revenue, total expense, net income (revenue minus expense), closing equity (equity plus net income), and a boolean 'balanced' that is True exactly when total assets equal liabilities plus closing equity. For example, with entries: (Cash 10000 D / Equity:Capital 10000 C), (Asset:Cash 5000 D / Liability:Loan 5000 C), (Asset:Equipment 2500 D / Asset:Cash 2500 C), (Asset:Cash 1200 D / Revenue:Sales 1200 C), (Expense:Rent 400 D / Asset:Cash 400 C), (Expense:Wages 250.50 D / Asset:Cash 250.50 C) \u2014 the report must show total assets 15549.50, total liabilities 5000.00, net income 549.50, closing equity 10549.50, and balanced True. Use only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0\")\n\nVALID_TYPES = {\"Asset\", \"Liability\", \"Equity\", \"Revenue\", \"Expense\"}\nDEBIT_NORMAL = {\"Asset\", \"Expense\"}\n\n\ndef to_money(value):\n \"\"\"Parse a numeric value into a Decimal quantized to cents (ROUND_HALF_UP).\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef account_type(account):\n category = account.split(\":\", 1)[0]\n if category not in VALID_TYPES:\n raise ValueError(\"unknown account category in account: {!r}\".format(account))\n return category\n\n\ndef validate_entry(entry, number):\n debits = ZERO\n credits = ZERO\n for account, side, amount in entry:\n amt = to_money(amount)\n account_type(account)\n if side == \"debit\":\n debits += amt\n elif side == \"credit\":\n credits += amt\n else:\n raise ValueError(\n \"entry {}: invalid side {!r} (expected 'debit' or 'credit')\".format(number, side)\n )\n if debits != credits:\n raise ValueError(\n \"entry {} is unbalanced: debits {} != credits {}\".format(number, debits, credits)\n )\n\n\ndef post_ledger(entries):\n \"\"\"Post all validated entries and return raw debit-positive balances per account.\"\"\"\n balances = defaultdict(lambda: ZERO)\n for number, entry in enumerate(entries, 1):\n validate_entry(entry, number)\n for account, side, amount in entry:\n amt = to_money(amount)\n if side == \"debit\":\n balances[account] += amt\n else:\n balances[account] -= amt\n return balances\n\n\ndef summarize(entries):\n raw_balances = post_ledger(entries)\n\n accounts = {}\n totals = {t: ZERO for t in VALID_TYPES}\n\n for account in sorted(raw_balances):\n raw = raw_balances[account]\n atype = account_type(account)\n # Normalize so debit-normal categories are debit-positive and the\n # credit-normal categories are reported as positive credit balances.\n normal = raw if atype in DEBIT_NORMAL else -raw\n accounts[account] = normal.quantize(CENT, rounding=ROUND_HALF_UP)\n totals[atype] += normal\n\n total_assets = totals[\"Asset\"].quantize(CENT, rounding=ROUND_HALF_UP)\n total_liabilities = totals[\"Liability\"].quantize(CENT, rounding=ROUND_HALF_UP)\n total_equity = totals[\"Equity\"].quantize(CENT, rounding=ROUND_HALF_UP)\n total_revenue = totals[\"Revenue\"].quantize(CENT, rounding=ROUND_HALF_UP)\n total_expense = totals[\"Expense\"].quantize(CENT, rounding=ROUND_HALF_UP)\n\n net_income = (total_revenue - total_expense).quantize(CENT, rounding=ROUND_HALF_UP)\n closing_equity = (total_equity + net_income).quantize(CENT, rounding=ROUND_HALF_UP)\n balanced = total_assets == (total_liabilities + closing_equity)\n\n return {\n \"accounts\": accounts,\n \"total_assets\": total_assets,\n \"total_liabilities\": total_liabilities,\n \"total_equity\": total_equity,\n \"total_revenue\": total_revenue,\n \"total_expense\": total_expense,\n \"net_income\": net_income,\n \"closing_equity\": closing_equity,\n \"balanced\": balanced,\n }\n\n\nif __name__ == \"__main__\":\n D, C = \"debit\", \"credit\"\n entries = [\n [(\"Asset:Cash\", D, \"10000\"), (\"Equity:Capital\", C, \"10000\")],\n [(\"Asset:Cash\", D, \"5000\"), (\"Liability:Loan\", C, \"5000\")],\n [(\"Asset:Equipment\", D, \"2500\"), (\"Asset:Cash\", C, \"2500\")],\n [(\"Asset:Cash\", D, \"1200\"), (\"Revenue:Sales\", C, \"1200\")],\n [(\"Expense:Rent\", D, \"400\"), (\"Asset:Cash\", C, \"400\")],\n [(\"Expense:Wages\", D, \"250.50\"), (\"Asset:Cash\", C, \"250.50\")],\n ]\n\n report = summarize(entries)\n\n assert report[\"total_assets\"] == Decimal(\"15549.50\")\n assert report[\"total_liabilities\"] == Decimal(\"5000.00\")\n assert report[\"net_income\"] == Decimal(\"549.50\")\n assert report[\"closing_equity\"] == Decimal(\"10549.50\")\n assert report[\"balanced\"] is True\n assert report[\"accounts\"][\"Asset:Cash\"] == Decimal(\"13049.50\")\n\n for key, value in report.items():\n if key != \"accounts\":\n print(\"{}: {}\".format(key, value))\n print(\"accounts:\")\n for account, balance in report[\"accounts\"].items():\n print(\" {}: {}\".format(account, balance))\n\n # An unbalanced entry must raise ValueError mentioning the entry number.\n try:\n summarize([[(\"Asset:Cash\", D, \"100\"), (\"Equity:Capital\", C, \"90\")]])\n except ValueError as exc:\n assert \"entry 1\" in str(exc)\n else:\n raise AssertionError(\"expected ValueError for unbalanced entry\")"}], "meta": {"idx": 2460, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1618, "latency_s": 50.8}} +{"prompt": [{"role": "user", "content": "You are building the fixed-asset ledger for a small business. Write a function `depreciation_schedule(cost, salvage, life, rate=None)` that returns a depreciation schedule as a list of tuples `(year, depreciation_expense, accumulated_depreciation, book_value)`. Use `Decimal` for all monetary values with ROUND_HALF_UP quantization to cents. If `rate` is None, use the straight-line method: each year's expense is `(cost - salvage) / life`, with the final year absorbing any rounding remainder so the final book value equals salvage exactly. If `rate` is given as a Decimal (e.g. Decimal('0.40') for double-declining balance), use the declining-balance method: each year's expense is `book_value * rate`, but never depreciate below salvage; if the computed expense would take book value below salvage, cap it at `book_value - salvage`. For example, with cost=Decimal('10000.00'), salvage=Decimal('1000.00'), life=5, rate=Decimal('0.40') the schedule should end with book value exactly Decimal('1000.00') and the first year's expense is Decimal('4000.00'). The function must raise ValueError if salvage > cost, life <= 0, or a declining-balance rate is not between 0 and 1 exclusive."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _q(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef depreciation_schedule(cost, salvage, life, rate=None):\n cost = Decimal(str(cost))\n salvage = Decimal(str(salvage))\n if salvage > cost:\n raise ValueError('salvage cannot exceed cost')\n if life <= 0:\n raise ValueError('life must be positive')\n if rate is not None:\n rate = Decimal(str(rate))\n if not (Decimal('0') < rate < Decimal('1')):\n raise ValueError('rate must be between 0 and 1 exclusive')\n\n schedule = []\n accumulated = Decimal('0.00')\n book_value = _q(cost)\n\n if rate is None:\n per_year = _q((cost - salvage) / Decimal(life))\n for year in range(1, life + 1):\n if year < life:\n expense = per_year\n else:\n expense = _q(cost - salvage - accumulated)\n accumulated = _q(accumulated + expense)\n book_value = _q(cost - accumulated)\n schedule.append((year, expense, accumulated, book_value))\n else:\n year = 1\n while book_value > salvage:\n expense = _q(book_value * rate)\n if book_value - expense < salvage:\n expense = _q(book_value - salvage)\n if expense <= 0:\n break\n accumulated = _q(accumulated + expense)\n book_value = _q(book_value - expense)\n schedule.append((year, expense, accumulated, book_value))\n year += 1\n\n return schedule\n\nif __name__ == '__main__':\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 5, Decimal('0.40')):\n print(row)\n print()\n for row in depreciation_schedule(Decimal('10000.00'), Decimal('1000.00'), 3):\n print(row)"}], "meta": {"idx": 2464, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 774, "latency_s": 11.4}} +{"prompt": [{"role": "user", "content": "A bookkeeper must build an amortization ledger for a loan with principal P, annual nominal interest rate r (as a decimal, e.g. 0.12), and n monthly payments. Interest for each month is computed as the periodic interest on the outstanding balance (balance * r / 12), rounded to the nearest cent using Decimal ROUND_HALF_UP. Each payment is a fixed annuity amount A = P * i / (1 - (1+i)^-n) where i = r/12, also rounded to the nearest cent. Each month, interest is charged first, then the payment is applied: new_balance = old_balance + interest - payment. On the final month, the payment is adjusted to exactly clear the remaining balance (payment = old_balance + interest), so the ledger ends at 0.00. Write a function amortize(principal, annual_rate, months) that takes Decimal or string values and returns a list of ledger entries as tuples (payment_number, interest, payment, balance), all Decimals rounded to cents, plus the final regular payment amount A as the second element of a returned tuple (entries, A). Example: amortize('1000.00', '0.12', 12) should produce 12 entries, first entry (1, Decimal('10.00'), Decimal('88.85'), Decimal('921.15')) \u2014 interest 1000*0.01 = 10.00, payment 88.85 \u2014 and the final balance must be exactly Decimal('0.00')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _round(x):\n return x.quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortize(principal, annual_rate, months):\n P = Decimal(str(principal))\n r = Decimal(str(annual_rate))\n n = int(months)\n i = r / Decimal(12)\n\n if i == 0:\n A = _round(P / n)\n else:\n A = _round(P * i / (Decimal(1) - (Decimal(1) + i) ** (-n)))\n\n entries = []\n balance = _round(P)\n for k in range(1, n + 1):\n interest = _round(balance * i)\n if k == n:\n payment = _round(balance + interest)\n else:\n payment = A\n balance = _round(balance + interest - payment)\n if k == n:\n balance = Decimal('0.00')\n entries.append((k, interest, payment, balance))\n return entries, A\n\nif __name__ == '__main__':\n entries, A = amortize('1000.00', '0.12', 12)\n print('Regular payment:', A)\n for e in entries:\n print(e)\n assert entries[0] == (1, Decimal('10.00'), Decimal('88.85'), Decimal('921.15'))\n assert entries[-1][3] == Decimal('0.00')"}], "meta": {"idx": 2461, "topic": "interest calculation and payment schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 606, "latency_s": 45.7}} +{"prompt": [{"role": "user", "content": "Implement `generate_closing_entries(accounts)` for period-end closing, where `accounts` is a list of tuples `(name, kind, side, amount)` with `kind` in {'permanent','revenue','expense','dividend'}, `side` being 'D' or 'C' (the side the balance actually sits on, so contra accounts like Sales Returns with a debit balance are handled correctly), and `amount` a Decimal or string that must first be rounded to cents with ROUND_HALF_UP. First validate the trial balance: the sum of debit-side balances must equal the sum of credit-side balances, otherwise raise ValueError; negative amounts are also invalid. Then return the closing journal entries in order: (1) close all revenue accounts (including contra-revenue) to Income Summary by reversing each account's balance, (2) close all expense accounts (including contra-expense) to Income Summary, (3) close Income Summary's net balance to Retained Earnings (net income credits RE, net loss debits RE; skip if zero), (4) close Dividend accounts to Retained Earnings. Each entry is a dict {'memo': str, 'lines': [(account, debit, credit), ...]} with Decimal cent amounts; every entry must balance exactly, zero-balance temporary accounts produce no lines, and a group with no accounts produces no entry. Worked example: the balanced trial balance [('Cash','permanent','D','3450.00'), ('Accounts Receivable','permanent','D','2500.00'), ('Equipment','permanent','D','4000.00'), ('Accounts Payable','permanent','C','1500.00'), ('Retained Earnings','permanent','C','5000.00'), ('Sales Revenue','revenue','C','12500.00'), ('Sales Returns & Allowances','revenue','D','500.00'), ('Rent Expense','expense','D','3000.00'), ('Salaries Expense','expense','D','4750.00'), ('Purchase Discounts','expense','C','200.00'), ('Dividends','dividend','D','1000.00')] (total debits = total credits = 19200.00) must produce four entries: revenue entry lines [('Sales Revenue',12500.00,0),('Sales Returns & Allowances',0,500.00),('Income Summary',0,12000.00)]; expense entry lines [('Rent Expense',0,3000.00),('Salaries Expense',0,4750.00),('Purchase Discounts',200.00,0),('Income Summary',7550.00,0)]; Income Summary closing lines [('Income Summary',4450.00,0),('Retained Earnings',0,4450.00)] for the net income of 4450.00; and dividend lines [('Retained Earnings',1000.00,0),('Dividends',0,1000.00)]."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\nKINDS = {\"permanent\", \"revenue\", \"expense\", \"dividend\"}\n\n\ndef _round_to_cent(value):\n \"\"\"Convert to Decimal and round to cents using ROUND_HALF_UP.\"\"\"\n return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef generate_closing_entries(accounts):\n \"\"\"Generate period-end closing entries.\n\n accounts: iterable of (name, kind, side, amount)\n kind in {'permanent','revenue','expense','dividend'}\n side in {'D','C'} -- the side on which the balance sits\n amount: Decimal/str, rounded to cents with ROUND_HALF_UP\n\n Returns a list of dicts: {'memo': str, 'lines': [(account, debit, credit), ...]}\n Raises ValueError on an unbalanced trial balance or invalid input.\n \"\"\"\n parsed = []\n total_debits = ZERO\n total_credits = ZERO\n\n for record in accounts:\n if len(record) != 4:\n raise ValueError(\"each account record must be (name, kind, side, amount)\")\n name, kind, side, amount = record\n if kind not in KINDS:\n raise ValueError(\"unknown account kind: {!r}\".format(kind))\n if side not in (\"D\", \"C\"):\n raise ValueError(\"invalid balance side: {!r}\".format(side))\n amt = _round_to_cent(amount)\n if amt < ZERO:\n raise ValueError(\"negative amount not allowed for account {!r}\".format(name))\n if side == \"D\":\n total_debits += amt\n else:\n total_credits += amt\n parsed.append((name, kind, side, amt))\n\n if total_debits != total_credits:\n raise ValueError(\n \"trial balance out of balance: debits {} != credits {}\".format(\n total_debits, total_credits\n )\n )\n\n entries = []\n # Totals posted to Income Summary while closing temporary accounts.\n is_debits = ZERO\n is_credits = ZERO\n\n def close_group(kind, memo):\n \"\"\"Close every non-zero balance of `kind` by reversing its side.\n\n The offsetting plug goes to Income Summary so the entry balances.\n Updates the Income Summary running totals via the enclosing scope.\n \"\"\"\n nonlocal is_debits, is_credits\n lines = []\n group_debits = ZERO\n group_credits = ZERO\n for name, k, side, amt in parsed:\n if k != kind or amt == ZERO:\n continue\n if side == \"C\":\n # Credit balance -> close by debiting the account,\n # crediting Income Summary.\n lines.append((name, amt, ZERO))\n group_debits += amt\n is_credits += amt\n else:\n # Debit balance (e.g. contra account) -> close by crediting\n # the account, debiting Income Summary.\n lines.append((name, ZERO, amt))\n group_credits += amt\n is_debits += amt\n if not lines:\n return None\n diff = group_debits - group_credits\n if diff > ZERO:\n lines.append((\"Income Summary\", ZERO, diff))\n elif diff < ZERO:\n lines.append((\"Income Summary\", -diff, ZERO))\n return {\"memo\": memo, \"lines\": lines}\n\n rev_entry = close_group(\"revenue\", \"Close revenue accounts to Income Summary\")\n if rev_entry:\n entries.append(rev_entry)\n\n exp_entry = close_group(\"expense\", \"Close expense accounts to Income Summary\")\n if exp_entry:\n entries.append(exp_entry)\n\n # Close Income Summary to Retained Earnings.\n net = is_credits - is_debits # positive = net income (credit balance)\n if net > ZERO:\n entries.append({\n \"memo\": \"Close Income Summary to Retained Earnings (net income)\",\n \"lines\": [(\"Income Summary\", net, ZERO),\n (\"Retained Earnings\", ZERO, net)],\n })\n elif net < ZERO:\n entries.append({\n \"memo\": \"Close Income Summary to Retained Earnings (net loss)\",\n \"lines\": [(\"Retained Earnings\", -net, ZERO),\n (\"Income Summary\", ZERO, -net)],\n })\n\n # Close Dividend accounts to Retained Earnings.\n div_lines = []\n div_debits = ZERO\n div_credits = ZERO\n for name, k, side, amt in parsed:\n if k != \"dividend\" or amt == ZERO:\n continue\n if side == \"D\":\n div_lines.append((name, ZERO, amt)) # credit the dividend account\n div_debits += amt # offsetting debit goes to RE\n else:\n div_lines.append((name, amt, ZERO))\n div_credits += amt\n if div_lines:\n diff = div_debits - div_credits\n if diff > ZERO:\n div_lines.append((\"Retained Earnings\", diff, ZERO))\n elif diff < ZERO:\n div_lines.append((\"Retained Earnings\", ZERO, -diff))\n entries.append({\"memo\": \"Close Dividends to Retained Earnings\",\n \"lines\": div_lines})\n\n # Final integrity check: every closing entry must balance exactly.\n for entry in entries:\n debits = sum(line[1] for line in entry[\"lines\"])\n credits = sum(line[2] for line in entry[\"lines\"])\n if debits != credits:\n raise ValueError(\"unbalanced closing entry: \" + entry[\"memo\"])\n return entries\n\n\nif __name__ == \"__main__\":\n trial_balance = [\n (\"Cash\", \"permanent\", \"D\", \"3450.00\"),\n (\"Accounts Receivable\", \"permanent\", \"D\", \"2500.00\"),\n (\"Equipment\", \"permanent\", \"D\", \"4000.00\"),\n (\"Accounts Payable\", \"permanent\", \"C\", \"1500.00\"),\n (\"Retained Earnings\", \"permanent\", \"C\", \"5000.00\"),\n (\"Sales Revenue\", \"revenue\", \"C\", \"12500.00\"),\n (\"Sales Returns & Allowances\", \"revenue\", \"D\", \"500.00\"),\n (\"Rent Expense\", \"expense\", \"D\", \"3000.00\"),\n (\"Salaries Expense\", \"expense\", \"D\", \"4750.00\"),\n (\"Purchase Discounts\", \"expense\", \"C\", \"200.00\"),\n (\"Dividends\", \"dividend\", \"D\", \"1000.00\"),\n ]\n\n result = generate_closing_entries(trial_balance)\n\n assert len(result) == 4\n assert result[0][\"lines\"] == [\n (\"Sales Revenue\", Decimal(\"12500.00\"), ZERO),\n (\"Sales Returns & Allowances\", ZERO, Decimal(\"500.00\")),\n (\"Income Summary\", ZERO, Decimal(\"12000.00\")),\n ]\n assert result[1][\"lines\"] == [\n (\"Rent Expense\", ZERO, Decimal(\"3000.00\")),\n (\"Salaries Expense\", ZERO, Decimal(\"4750.00\")),\n (\"Purchase Discounts\", Decimal(\"200.00\"), ZERO),\n (\"Income Summary\", Decimal(\"7550.00\"), ZERO),\n ]\n assert result[2][\"lines\"] == [\n (\"Income Summary\", Decimal(\"4450.00\"), ZERO),\n (\"Retained Earnings\", ZERO, Decimal(\"4450.00\")),\n ]\n assert result[3][\"lines\"] == [\n (\"Retained Earnings\", Decimal(\"1000.00\"), ZERO),\n (\"Dividends\", ZERO, Decimal(\"1000.00\")),\n ]\n\n for entry in result:\n print(entry[\"memo\"])\n for account, debit, credit in entry[\"lines\"]:\n print(\" {:30s} {:>12} {:>12}\".format(\n account, debit, credit))\n\n # Rounding demonstration: 4750.005 rounds to 4750.01 (ROUND_HALF_UP).\n assert _round_to_cent(\"4750.005\") == Decimal(\"4750.01\")\n\n # Unbalanced trial balance must raise ValueError.\n try:\n generate_closing_entries(\n [(\"Cash\", \"permanent\", \"D\", \"100.00\"),\n (\"Sales Revenue\", \"revenue\", \"C\", \"90.00\")]\n )\n raise AssertionError(\"expected ValueError for unbalanced trial balance\")\n except ValueError:\n pass\n\n print(\"All checks passed.\")"}], "meta": {"idx": 2458, "topic": "period-end closing entries and routines", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2593, "latency_s": 135.2}} +{"prompt": [{"role": "user", "content": "You are given a list of journal entries affecting a small general ledger. Each entry is a tuple (account, side, amount) where side is 'D' for debit or 'C' for credit, and amounts are strings representing exact decimal money values. Write a function t_account_balances(entries) that groups postings by account into T-accounts, computes the total debits and total credits per account, and returns a dict mapping each account name to a dict {'debits': Decimal, 'credits': Decimal, 'balance': Decimal, 'balance_side': 'D' or 'C'}. The balance is the absolute difference between total debits and total credits; balance_side is 'D' if debits exceed credits, otherwise 'C' (a zero difference reports side 'C'). All arithmetic must use Decimal with ROUND_HALF_UP rounding applied to the totals and balance to 2 decimal places. For example, entries [('Cash', 'D', '100.00'), ('Cash', 'C', '25.505'), ('Revenue', 'C', '75.505')] gives Cash debits 100.00, credits 25.51 (rounded), balance 74.49 with side 'D', and Revenue credits 75.51 with balance_side 'C'. Accounts with no entries should not appear in the result."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom collections import defaultdict\n\n\ndef _round2(value):\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\ndef t_account_balances(entries):\n totals = defaultdict(lambda: {'debits': Decimal('0'), 'credits': Decimal('0')})\n for account, side, amount in entries:\n amt = Decimal(str(amount))\n if side == 'D':\n totals[account]['debits'] += amt\n elif side == 'C':\n totals[account]['credits'] += amt\n else:\n raise ValueError(f\"Invalid side: {side!r}\")\n\n result = {}\n for account, tt in totals.items():\n debits = _round2(tt['debits'])\n credits = _round2(tt['credits'])\n balance = _round2(abs(debits - credits))\n side = 'D' if debits > credits else 'C'\n result[account] = {\n 'debits': debits,\n 'credits': credits,\n 'balance': balance,\n 'balance_side': side,\n }\n return result\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', 'D', '100.00'),\n ('Cash', 'C', '25.505'),\n ('Revenue', 'C', '75.505'),\n ]\n print(t_account_balances(entries))"}], "meta": {"idx": 2468, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 590, "latency_s": 5.4}} +{"prompt": [{"role": "user", "content": "Implement a strict double-entry Journal class together with a comprehensive unittest test suite. A journal is opened with a fixed set of account names; an entry is a dict mapping an account name to a Decimal amount (debit positive, credit negative), and post(entry_date, entry) applies the entry only if every amount is a finite, non-zero Decimal (floats and ints must be rejected), every account exists, the amounts quantized to cents with ROUND_HALF_UP sum exactly to zero, and entry_date is a datetime.date that is not earlier than the date of the last posted entry; otherwise the journal must remain completely unchanged and the appropriate exception is raised: InvalidAmountError, UnknownAccountError, UnbalancedEntryError, or OutOfOrderDateError. post_batch(entries) applies a sequence of (date, entry) pairs atomically, so if any entry fails validation the whole batch is rejected and no balances change. balance(account) returns an account balance to the cent, and trial_balance() returns a dict of all balances whose values must sum to zero. Worked example: with accounts {\"Cash\", \"Revenue\"}, posting date(2024,1,1) with {\"Cash\": Decimal(\"150.00\"), \"Revenue\": Decimal(\"-150.00\")} succeeds and leaves Cash at Decimal(\"150.00\"); posting {\"Cash\": Decimal(\"100.00\"), \"Revenue\": Decimal(\"-99.99\")} raises UnbalancedEntryError, and a subsequent attempt dated date(2023,12,31) raises OutOfOrderDateError. Write unit tests covering acceptance, every rejection path, atomic batch rollback, ROUND_HALF_UP behavior on Decimal(\"0.005\"), rejection of non-finite values like Decimal(\"NaN\"), and verification that a failed post leaves all balances untouched."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\nclass AccountingError(Exception):\n \"\"\"Base class for all journal errors.\"\"\"\n\n\nclass UnbalancedEntryError(AccountingError):\n pass\n\n\nclass InvalidAmountError(AccountingError):\n pass\n\n\nclass UnknownAccountError(AccountingError):\n pass\n\n\nclass OutOfOrderDateError(AccountingError):\n pass\n\n\nclass Journal:\n \"\"\"A strict double-entry journal with exact cent-level precision.\"\"\"\n\n def __init__(self, accounts):\n self._accounts = frozenset(accounts)\n self._balances = {a: ZERO for a in self._accounts}\n self._last_date = None\n\n @staticmethod\n def _quantize(amount):\n return amount.quantize(CENT, rounding=ROUND_HALF_UP)\n\n def _validate(self, entry_date, entry, prev_date):\n if not isinstance(entry_date, date):\n raise InvalidAmountError(\n \"entry_date must be a datetime.date, got %r\" % (type(entry_date).__name__,))\n if not entry:\n raise InvalidAmountError(\"an entry must contain at least one line\")\n for account, amount in entry.items():\n if account not in self._accounts:\n raise UnknownAccountError(\"unknown account: %r\" % (account,))\n if not isinstance(amount, Decimal):\n raise InvalidAmountError(\n \"amount for account %r must be Decimal, got %r\"\n % (account, type(amount).__name__))\n if not amount.is_finite():\n raise InvalidAmountError(\n \"amount for account %r must be finite, got %s\" % (account, amount))\n if self._quantize(amount) == ZERO:\n raise InvalidAmountError(\n \"zero amounts are not allowed on account %r\" % (account,))\n total = ZERO\n for amount in entry.values():\n total += self._quantize(amount)\n if total != ZERO:\n raise UnbalancedEntryError(\"entry is out of balance by %s\" % total)\n if prev_date is not None and entry_date < prev_date:\n raise OutOfOrderDateError(\n \"entry dated %s precedes last posted date %s\" % (entry_date, prev_date))\n\n def _apply(self, entry_date, entry):\n for account, amount in entry.items():\n self._balances[account] = self._quantize(self._balances[account] + amount)\n self._last_date = entry_date\n\n def post(self, entry_date, entry):\n \"\"\"Post a single balanced entry; raise on any rule violation.\"\"\"\n self._validate(entry_date, entry, self._last_date)\n self._apply(entry_date, entry)\n\n def post_batch(self, entries):\n \"\"\"Post a sequence of (date, entry) pairs atomically.\"\"\"\n entries = list(entries)\n prev = self._last_date\n for entry_date, entry in entries:\n self._validate(entry_date, entry, prev)\n prev = entry_date\n for entry_date, entry in entries:\n self._apply(entry_date, entry)\n\n def balance(self, account):\n if account not in self._accounts:\n raise UnknownAccountError(\"unknown account: %r\" % (account,))\n return self._balances[account]\n\n def trial_balance(self):\n \"\"\"Return a copy of every account balance; the values must sum to zero.\"\"\"\n return dict(self._balances)\n\n\nclass JournalTests(unittest.TestCase):\n\n def setUp(self):\n self.journal = Journal([\"Cash\", \"Revenue\", \"Expenses\"])\n\n def _snapshot(self):\n return self.journal.trial_balance()\n\n # ---- acceptance ----------------------------------------------------\n\n def test_valid_post_updates_balances(self):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"150.00\"),\n \"Revenue\": Decimal(\"-150.00\"),\n })\n self.journal.post(date(2024, 1, 2), {\n \"Expenses\": Decimal(\"30.00\"),\n \"Cash\": Decimal(\"-30.00\"),\n })\n self.assertEqual(self.journal.balance(\"Cash\"), Decimal(\"120.00\"))\n self.assertEqual(self.journal.balance(\"Revenue\"), Decimal(\"-150.00\"))\n self.assertEqual(self.journal.balance(\"Expenses\"), Decimal(\"30.00\"))\n\n def test_same_day_entries_allowed(self):\n entry = {\"Cash\": Decimal(\"10.00\"), \"Revenue\": Decimal(\"-10.00\")}\n self.journal.post(date(2024, 1, 1), entry)\n self.journal.post(date(2024, 1, 1), entry) # non-decreasing dates are fine\n self.assertEqual(self.journal.balance(\"Cash\"), Decimal(\"20.00\"))\n\n def test_trial_balance_sums_to_zero(self):\n self.journal.post(date(2024, 3, 1), {\n \"Cash\": Decimal(\"12.34\"),\n \"Expenses\": Decimal(\"7.66\"),\n \"Revenue\": Decimal(\"-20.00\"),\n })\n tb = self.journal.trial_balance()\n self.assertEqual(sum(tb.values(), ZERO), ZERO)\n self.assertEqual(tb, {\n \"Cash\": Decimal(\"12.34\"),\n \"Revenue\": Decimal(\"-20.00\"),\n \"Expenses\": Decimal(\"7.66\"),\n })\n\n # ---- rejection paths -----------------------------------------------\n\n def test_unbalanced_entry_rejected_state_unchanged(self):\n before = self._snapshot()\n with self.assertRaises(UnbalancedEntryError):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"100.00\"),\n \"Revenue\": Decimal(\"-99.99\"),\n })\n self.assertEqual(self.journal.trial_balance(), before)\n self.assertIsNone(self.journal._last_date)\n\n def test_float_amount_rejected(self):\n for bad in (100.0, 99):\n with self.subTest(value=bad):\n with self.assertRaises(InvalidAmountError):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"10.00\"),\n \"Revenue\": bad,\n })\n\n def test_non_finite_and_zero_amounts_rejected(self):\n for bad in (Decimal(\"NaN\"), Decimal(\"Infinity\"), Decimal(\"-Infinity\"),\n Decimal(\"0.00\"), Decimal(\"0.004\")):\n with self.subTest(value=bad):\n with self.assertRaises(InvalidAmountError):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": bad,\n \"Revenue\": Decimal(\"-10.00\"),\n })\n\n def test_unknown_account_rejected(self):\n with self.assertRaises(UnknownAccountError):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"10.00\"),\n \"Accounts Payable\": Decimal(\"-10.00\"),\n })\n\n def test_empty_entry_rejected(self):\n with self.assertRaises(InvalidAmountError):\n self.journal.post(date(2024, 1, 1), {})\n\n def test_non_date_rejected(self):\n with self.assertRaises(InvalidAmountError):\n self.journal.post(\"2024-01-01\", {\n \"Cash\": Decimal(\"10.00\"),\n \"Revenue\": Decimal(\"-10.00\"),\n })\n\n def test_date_ordering_enforced(self):\n self.journal.post(date(2024, 1, 2), {\n \"Cash\": Decimal(\"5.00\"), \"Revenue\": Decimal(\"-5.00\")})\n before = self._snapshot()\n with self.assertRaises(OutOfOrderDateError):\n self.journal.post(date(2023, 12, 31), {\n \"Cash\": Decimal(\"5.00\"), \"Revenue\": Decimal(\"-5.00\")})\n self.assertEqual(self.journal.trial_balance(), before)\n\n def test_balance_unknown_account_raises(self):\n with self.assertRaises(UnknownAccountError):\n self.journal.balance(\"Equity\")\n\n # ---- atomic batch ---------------------------------------------------\n\n def test_post_batch_valid_sequence(self):\n self.journal.post_batch([\n (date(2024, 1, 1), {\"Cash\": Decimal(\"100.00\"),\n \"Revenue\": Decimal(\"-100.00\")}),\n (date(2024, 1, 3), {\"Expenses\": Decimal(\"25.00\"),\n \"Cash\": Decimal(\"-25.00\")}),\n ])\n self.assertEqual(self.journal.balance(\"Cash\"), Decimal(\"75.00\"))\n self.assertEqual(self.journal.balance(\"Revenue\"), Decimal(\"-100.00\"))\n self.assertEqual(self.journal.balance(\"Expenses\"), Decimal(\"25.00\"))\n\n def test_post_batch_atomic_rollback(self):\n self.journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"50.00\"), \"Revenue\": Decimal(\"-50.00\")})\n before = self._snapshot()\n batch = [\n (date(2024, 1, 2), {\"Expenses\": Decimal(\"10.00\"),\n \"Cash\": Decimal(\"-10.00\")}),\n (date(2024, 1, 3), {\"Cash\": Decimal(\"1.00\"),\n \"Ghost Account\": Decimal(\"-1.00\")}),\n ]\n with self.assertRaises(UnknownAccountError):\n self.journal.post_batch(batch)\n # Nothing from the batch may have been applied.\n self.assertEqual(self.journal.trial_balance(), before)\n self.assertEqual(self.journal.balance(\"Expenses\"), Decimal(\"0.00\"))\n self.assertEqual(self.journal._last_date, date(2024, 1, 1))\n\n def test_post_batch_rejects_decreasing_dates_inside_batch(self):\n before = self._snapshot()\n batch = [\n (date(2024, 1, 5), {\"Cash\": Decimal(\"1.00\"),\n \"Revenue\": Decimal(\"-1.00\")}),\n (date(2024, 1, 4), {\"Cash\": Decimal(\"2.00\"),\n \"Revenue\": Decimal(\"-2.00\")}),\n ]\n with self.assertRaises(OutOfOrderDateError):\n self.journal.post_batch(batch)\n self.assertEqual(self.journal.trial_balance(), before)\n\n # ---- precise rounding -------------------------------------------------\n\n def test_rounding_half_up_on_half_cent(self):\n journal = Journal([\"Cash\", \"Revenue\"])\n journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"0.005\"),\n \"Revenue\": Decimal(\"-0.005\"),\n })\n # ROUND_HALF_UP sends 0.005 to 0.01 and -0.005 to -0.01.\n self.assertEqual(journal.balance(\"Cash\"), Decimal(\"0.01\"))\n self.assertEqual(journal.balance(\"Revenue\"), Decimal(\"-0.01\"))\n self.assertEqual(sum(journal.trial_balance().values(), ZERO), ZERO)\n\n def test_rounding_can_break_balance_of_unquantized_sides(self):\n # 0.014 rounds down to 0.01 while -0.015 rounds to -0.02, so the\n # quantized amounts do not net to zero and the entry is rejected.\n journal = Journal([\"Cash\", \"Revenue\"])\n with self.assertRaises(UnbalancedEntryError):\n journal.post(date(2024, 1, 1), {\n \"Cash\": Decimal(\"0.014\"),\n \"Revenue\": Decimal(\"-0.015\"),\n })\n self.assertEqual(journal.trial_balance(), {\"Cash\": ZERO, \"Revenue\": ZERO})\n\n\nif __name__ == \"__main__\":\n unittest.main()"}], "meta": {"idx": 2450, "topic": "unit tests for accounting functions", "difficulty": "hard", "provider": "deepinfra", "in_tokens": 197, "out_tokens": 6376, "latency_s": 102.9}} +{"prompt": [{"role": "user", "content": "Implement a general ledger with T-account support using precise Decimal arithmetic. Create an `Account` class with a name, and `debit`/`credit` methods that record entries and maintain running balances, plus a `balance()` method returning the net balance (debits minus credits) as a Decimal. Create a `Ledger` class with a `post(debit_account, credit_account, amount, description)` method that atomically posts a double-entry (refuse and raise `ValueError` if the amount is negative or zero, or if either account name is unknown), and an `account(name)` method returning the Account, plus an `add_account(name)` method. Finally, implement `trial_balance(ledger)` returning a dict mapping each account name to its Decimal balance; the sum of all balances must equal Decimal('0.00'). Example: with accounts 'Cash' and 'Revenue', posting Cash->Revenue 150.00 yields {'Cash': Decimal('150.00'), 'Revenue': Decimal('-150.00')} and total 0.00. Round all posted amounts to 2 decimal places using ROUND_HALF_UP at posting time."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\nclass Account:\n def __init__(self, name):\n self.name = name\n self.debits = Decimal('0.00')\n self.credits = Decimal('0.00')\n self.entries = []\n\n def debit(self, amount, description=''):\n amt = Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n self.debits += amt\n self.entries.append(('debit', amt, description))\n\n def credit(self, amount, description=''):\n amt = Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n self.credits += amt\n self.entries.append(('credit', amt, description))\n\n def balance(self):\n return (self.debits - self.credits).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nclass Ledger:\n def __init__(self):\n self.accounts = {}\n\n def add_account(self, name):\n if name not in self.accounts:\n self.accounts[name] = Account(name)\n return self.accounts[name]\n\n def account(self, name):\n if name not in self.accounts:\n raise ValueError('Unknown account: {}'.format(name))\n return self.accounts[name]\n\n def post(self, debit_account, credit_account, amount, description=''):\n amt = Decimal(amount)\n if amt <= 0:\n raise ValueError('Amount must be positive')\n debit_acc = self.account(debit_account)\n credit_acc = self.account(credit_account)\n debit_acc.debit(amt, description)\n credit_acc.credit(amt, description)\n\n\ndef trial_balance(ledger):\n return {name: acc.balance() for name, acc in ledger.accounts.items()}\n\n\nif __name__ == '__main__':\n ledger = Ledger()\n ledger.add_account('Cash')\n ledger.add_account('Revenue')\n ledger.post('Cash', 'Revenue', '150.00', 'Initial sale')\n ledger.post('Revenue', 'Cash', '50.255', 'Refund')\n tb = trial_balance(ledger)\n print(tb)\n print('Total:', sum(tb.values()))\n assert tb == {'Cash': Decimal('99.75'), 'Revenue': Decimal('-99.75')}\n assert sum(tb.values()) == Decimal('0.00')\n try:\n ledger.post('Cash', 'Rent', '10.00')\n except ValueError as e:\n print('Caught expected error:', e)\n try:\n ledger.post('Cash', 'Revenue', '-5.00')\n except ValueError as e:\n print('Caught expected error:', e)"}], "meta": {"idx": 2469, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 857, "latency_s": 8.4}} +{"prompt": [{"role": "user", "content": "You are given a chronological log of petty-cash events for a fund run on the imprest system, where each event is a dict with a \"type\" of \"open\", \"disburse\", \"split_disburse\", \"count\", or \"replenish\". An \"open\" event (which must come first and occur only once) sets the imprest float; a \"disburse\" event carries a unique voucher id, a positive amount, and a category; a \"split_disburse\" event carries a voucher id, an amount, and an \"allocation\" mapping of at least two categories to positive integer weights, and the amount must be divided among the categories by the largest-remainder method (floor each exact share to cents, then hand out the leftover cents one at a time to the categories with the largest fractional parts, breaking ties alphabetically); a \"count\" event records physical cash on hand, whose difference from the ledger balance is a \"minor\" discrepancy when its absolute value is at most 0.01 and a \"major\" one otherwise, and the ledger balance is reset to the counted cash; a \"replenish\" event restores the fund to the imprest amount by adding (imprest \u2212 current ledger balance), which must be non-negative. All money values are strings that must be handled with Decimal and rounded to cents with ROUND_HALF_UP, and you must raise ValueError with a descriptive message for any invalid event (non-first or duplicate open, non-positive imprest, unknown type, missing fund, duplicate voucher, non-positive amount, disbursement exceeding the ledger balance, bad weights, negative counted cash, or a replenish that would require removing cash). The function process_petty_cash_log(events) must return a dict with keys \"final_balance\", \"total_disbursed\", \"total_replenished\", \"voucher_count\" (int), \"discrepancies\" (list of {\"event_index\", \"amount\", \"kind\"}), and \"category_totals\" (category to 2-decimal string), with all monetary values as 2-decimal strings. Worked example: for events [{\"type\":\"open\",\"imprest\":\"300.00\"}, {\"type\":\"disburse\",\"voucher\":\"V-1\",\"amount\":\"12.50\",\"category\":\"supplies\"}, {\"type\":\"split_disburse\",\"voucher\":\"V-2\",\"amount\":\"100.00\",\"allocation\":{\"misc\":1,\"supplies\":1,\"travel\":1}}, {\"type\":\"count\",\"cash_on_hand\":\"187.49\"}, {\"type\":\"replenish\"}, {\"type\":\"disburse\",\"voucher\":\"V-3\",\"amount\":\"75.00\",\"category\":\"travel\"}] the split gives misc 33.34 and supplies/travel 33.33 each, the count yields a minor discrepancy of \"-0.01\", replenishment is 112.51, and the result is {\"final_balance\":\"225.00\",\"total_disbursed\":\"187.50\",\"total_replenished\":\"112.51\",\"voucher_count\":3,\"discrepancies\":[{\"event_index\":3,\"amount\":\"-0.01\",\"kind\":\"minor\"}],\"category_totals\":{\"misc\":\"33.34\",\"supplies\":\"45.83\",\"travel\":\"108.33\"}}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nTOLERANCE = Decimal(\"0.01\")\n\n\ndef _to_money(value, ctx):\n if value is None:\n raise ValueError(f\"{ctx}: missing monetary value\")\n try:\n d = Decimal(str(value))\n except Exception:\n raise ValueError(f\"{ctx}: cannot parse amount {value!r}\")\n return d.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef _money_str(d):\n return str(d.quantize(CENT, rounding=ROUND_HALF_UP))\n\n\ndef _parse_weight(w, ctx):\n if isinstance(w, bool):\n raise ValueError(f\"{ctx}: invalid weight {w!r}\")\n if isinstance(w, int):\n val = w\n else:\n try:\n d = Decimal(str(w))\n except Exception:\n raise ValueError(f\"{ctx}: invalid weight {w!r}\")\n if d != d.to_integral_value():\n raise ValueError(f\"{ctx}: weight {w!r} is not an integer\")\n val = int(d)\n if val <= 0:\n raise ValueError(f\"{ctx}: weight {w!r} must be positive\")\n return val\n\n\ndef _largest_remainder_split(amount, allocation, ctx):\n weights = {}\n for cat, w in allocation.items():\n weights[cat] = _parse_weight(w, ctx)\n if len(weights) < 2:\n raise ValueError(f\"{ctx}: split needs at least two categories\")\n total_w = sum(weights.values())\n exact = {c: amount * Decimal(weights[c]) / Decimal(total_w) for c in weights}\n base = {c: exact[c].quantize(CENT, rounding=ROUND_DOWN) for c in weights}\n leftover = amount - sum(base.values())\n leftover_cents = int((leftover / CENT).to_integral_value(rounding=ROUND_HALF_UP))\n order = sorted(weights, key=lambda c: (-(exact[c] - base[c]), c))\n for c in order[:leftover_cents]:\n base[c] += CENT\n if sum(base.values()) != amount:\n raise ValueError(f\"{ctx}: split does not sum to amount\")\n return base\n\n\ndef process_petty_cash_log(events):\n imprest = None\n ledger = None\n vouchers = set()\n voucher_count = 0\n total_disbursed = Decimal(\"0\")\n total_replenished = Decimal(\"0\")\n category_totals = {}\n discrepancies = []\n\n for idx, ev in enumerate(events):\n ctx = f\"event {idx}\"\n if not isinstance(ev, dict) or \"type\" not in ev:\n raise ValueError(f\"{ctx}: malformed event\")\n etype = ev[\"type\"]\n\n if etype == \"open\":\n if imprest is not None:\n raise ValueError(f\"{ctx}: fund already open\")\n imprest = _to_money(ev.get(\"imprest\"), ctx)\n if imprest <= 0:\n raise ValueError(f\"{ctx}: imprest must be positive\")\n ledger = imprest\n\n elif etype in (\"disburse\", \"split_disburse\"):\n if ledger is None:\n raise ValueError(f\"{ctx}: fund not open\")\n voucher = ev.get(\"voucher\")\n if voucher is None:\n raise ValueError(f\"{ctx}: missing voucher id\")\n if voucher in vouchers:\n raise ValueError(f\"{ctx}: duplicate voucher {voucher!r}\")\n amount = _to_money(ev.get(\"amount\"), ctx)\n if amount <= 0:\n raise ValueError(f\"{ctx}: amount must be positive\")\n if amount > ledger:\n raise ValueError(f\"{ctx}: disbursement {_money_str(amount)} exceeds ledger balance {_money_str(ledger)}\")\n if etype == \"disburse\":\n cat = ev.get(\"category\")\n if not cat:\n raise ValueError(f\"{ctx}: missing category\")\n alloc = {cat: amount}\n else:\n allocation = ev.get(\"allocation\")\n if not isinstance(allocation, dict) or not allocation:\n raise ValueError(f\"{ctx}: missing allocation\")\n alloc = _largest_remainder_split(amount, allocation, ctx)\n for cat, part in alloc.items():\n category_totals[cat] = category_totals.get(cat, Decimal(\"0\")) + part\n ledger -= amount\n total_disbursed += amount\n vouchers.add(voucher)\n voucher_count += 1\n\n elif etype == \"count\":\n if ledger is None:\n raise ValueError(f\"{ctx}: fund not open\")\n cash = _to_money(ev.get(\"cash_on_hand\"), ctx)\n if cash < 0:\n raise ValueError(f\"{ctx}: counted cash cannot be negative\")\n diff = cash - ledger\n kind = \"minor\" if abs(diff) <= TOLERANCE else \"major\"\n discrepancies.append({\n \"event_index\": idx,\n \"amount\": _money_str(diff),\n \"kind\": kind,\n })\n ledger = cash\n\n elif etype == \"replenish\":\n if ledger is None:\n raise ValueError(f\"{ctx}: fund not open\")\n refill = imprest - ledger\n if refill < 0:\n raise ValueError(f\"{ctx}: ledger {_money_str(ledger)} exceeds imprest {_money_str(imprest)}; cannot replenish\")\n total_replenished += refill\n ledger = imprest\n\n else:\n raise ValueError(f\"{ctx}: unknown event type {etype!r}\")\n\n if ledger is None:\n raise ValueError(\"log contains no fund-opening event\")\n\n return {\n \"final_balance\": _money_str(ledger),\n \"total_disbursed\": _money_str(total_disbursed),\n \"total_replenished\": _money_str(total_replenished),\n \"voucher_count\": voucher_count,\n \"discrepancies\": discrepancies,\n \"category_totals\": {c: _money_str(v) for c, v in sorted(category_totals.items())},\n }\n\n\nif __name__ == \"__main__\":\n example = [\n {\"type\": \"open\", \"imprest\": \"300.00\"},\n {\"type\": \"disburse\", \"voucher\": \"V-1\", \"amount\": \"12.50\", \"category\": \"supplies\"},\n {\"type\": \"split_disburse\", \"voucher\": \"V-2\", \"amount\": \"100.00\",\n \"allocation\": {\"misc\": 1, \"supplies\": 1, \"travel\": 1}},\n {\"type\": \"count\", \"cash_on_hand\": \"187.49\"},\n {\"type\": \"replenish\"},\n {\"type\": \"disburse\", \"voucher\": \"V-3\", \"amount\": \"75.00\", \"category\": \"travel\"},\n ]\n result = process_petty_cash_log(example)\n print(result)\n assert result == {\n \"final_balance\": \"225.00\",\n \"total_disbursed\": \"187.50\",\n \"total_replenished\": \"112.51\",\n \"voucher_count\": 3,\n \"discrepancies\": [{\"event_index\": 3, \"amount\": \"-0.01\", \"kind\": \"minor\"}],\n \"category_totals\": {\"misc\": \"33.34\", \"supplies\": \"45.83\", \"travel\": \"108.33\"},\n }\n print(\"example verified\")"}], "meta": {"idx": 2465, "topic": "petty cash logs and replenishment", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 2419, "latency_s": 80.6}} +{"prompt": [{"role": "user", "content": "You are building a small bookkeeping helper for a multi-rate sales tax system. Given a list of invoice line items, each described by a tuple (description, net_amount_str, tax_rate_str), compute for each line the tax amount rounded half-up to 2 decimal places, and the gross amount (net + tax). Then produce a tax summary report: for each distinct tax rate, the total net and total tax of the lines at that rate, with totals also rounded half-up to 2 decimals. Finally, return the grand total gross across all lines. All monetary computations must use Decimal to avoid float errors, and rounding must be ROUND_HALF_UP. Input amounts and rates are strings (e.g., rate '0.07' means 7%). Example: lines = [('Book', '10.05', '0.05'), ('Laptop', '999.99', '0.20')]. For the Book line, tax = 10.05 * 0.05 = 0.5025 -> 0.50, gross = 10.55. For the Laptop line, tax = 999.99 * 0.20 = 199.998 -> 200.00, gross = 1199.99. The summary has two rate groups, and the grand total gross is 10.55 + 1199.99 = 1210.54. Write a function tax_report(lines) that returns a dict with keys 'lines' (list of dicts with description, net, tax, gross as strings with 2 decimals), 'summary' (dict mapping rate string to {'net': ..., 'tax': ...}), and 'total_gross' (string with 2 decimals)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _round2(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef _fmt(value):\n return str(_round2(value))\n\n\ndef tax_report(lines):\n result_lines = []\n summary = {}\n total_gross = Decimal('0')\n\n for description, net_str, rate_str in lines:\n net = Decimal(net_str)\n rate = Decimal(rate_str)\n tax = _round2(net * rate)\n gross = _round2(net + tax)\n\n result_lines.append({\n 'description': description,\n 'net': _fmt(net),\n 'tax': _fmt(tax),\n 'gross': _fmt(gross),\n })\n\n if rate_str not in summary:\n summary[rate_str] = {'net': Decimal('0'), 'tax': Decimal('0')}\n summary[rate_str]['net'] += net\n summary[rate_str]['tax'] += tax\n\n total_gross += gross\n\n summary_out = {\n rate_str: {\n 'net': _fmt(vals['net']),\n 'tax': _fmt(vals['tax']),\n }\n for rate_str, vals in summary.items()\n }\n\n return {\n 'lines': result_lines,\n 'summary': summary_out,\n 'total_gross': _fmt(total_gross),\n }\n\n\nif __name__ == '__main__':\n lines = [\n ('Book', '10.05', '0.05'),\n ('Laptop', '999.99', '0.20'),\n ('Pen', '0.85', '0.05'),\n ]\n report = tax_report(lines)\n print(report['lines'])\n print(report['summary'])\n print(report['total_gross'])"}], "meta": {"idx": 2470, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 701, "latency_s": 8.6}} +{"prompt": [{"role": "user", "content": "You are building the amortization engine for a small lending ledger. Given a loan principal (exact cents), an annual nominal interest rate in percent (monthly rate = annual rate / 12 / 100), a term in months, and a mapping of month number to an extra principal payment, produce the full amortization schedule. The scheduled monthly payment is P*r/(1-(1+r)^-n) rounded to the nearest cent with ROUND_HALF_UP (or principal/term when the rate is zero); each month the interest is round(balance * r) to cents, the principal portion of the regular payment is payment minus interest, and any extra principal scheduled for that month is applied after the regular payment, capped at the remaining balance. If the regular payment would cover the remaining balance plus its interest, the loan pays off that month with a final payment of exactly balance + interest (any extra for that payoff month is ignored). The function must return the schedule rows (month, payment, interest, principal, extra, ending balance), the payoff month, the total interest paid, and the total of all payments including extras, using Decimal throughout so every amount is exact to the cent. Worked example: principal 10000.00, annual rate 12.0, term 12, extras of 500.00 at months 3 and 6 \u2014 the scheduled payment is 888.49, month 1 has interest 100.00 and ending balance 9211.51, and the loan pays off at month 11 with a final payment of 701.22, total interest 586.12, and total paid 10586.12."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, getcontext\n\ngetcontext().prec = 28\nCENT = Decimal(\"0.01\")\n\n\ndef _round_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef amortize(principal, annual_rate_pct, term_months, extra_payments=None):\n \"\"\"Build a full amortization schedule with extra principal payments.\n\n Returns a dict with the scheduled payment, the schedule rows, the\n payoff month, total interest, and total amount paid (extras included).\n \"\"\"\n if extra_payments is None:\n extra_payments = {}\n\n principal = Decimal(str(principal)).quantize(CENT)\n annual_rate = Decimal(str(annual_rate_pct)) / Decimal(100)\n monthly_rate = annual_rate / Decimal(12)\n n = int(term_months)\n extra_by_month = {\n int(m): Decimal(str(a)).quantize(CENT)\n for m, a in extra_payments.items()\n }\n\n if monthly_rate == 0:\n payment = _round_cents(principal / Decimal(n))\n else:\n discount = (Decimal(1) + monthly_rate) ** (-n)\n payment = _round_cents(\n principal * monthly_rate / (Decimal(1) - discount)\n )\n\n schedule = []\n balance = principal\n month = 0\n total_interest = Decimal(\"0.00\")\n total_paid = Decimal(\"0.00\")\n\n while balance > 0:\n month += 1\n if month > 2 * n + 12:\n raise ValueError(\"loan failed to amortize; check inputs\")\n\n interest = _round_cents(balance * monthly_rate)\n\n if payment >= balance + interest:\n pay_amount = balance + interest\n principal_part = balance\n extra = Decimal(\"0.00\")\n new_balance = Decimal(\"0.00\")\n else:\n pay_amount = payment\n principal_part = payment - interest\n new_balance = balance - principal_part\n extra = extra_by_month.get(month, Decimal(\"0.00\"))\n if extra > new_balance:\n extra = new_balance\n new_balance -= extra\n\n schedule.append({\n \"month\": month,\n \"payment\": pay_amount,\n \"interest\": interest,\n \"principal\": principal_part,\n \"extra\": extra,\n \"balance\": new_balance,\n })\n total_interest += interest\n total_paid += pay_amount + extra\n balance = new_balance\n\n return {\n \"scheduled_payment\": payment,\n \"schedule\": schedule,\n \"payoff_month\": month,\n \"total_interest\": total_interest,\n \"total_paid\": total_paid,\n }\n\n\nif __name__ == \"__main__\":\n result = amortize(\n principal=\"10000.00\",\n annual_rate_pct=12.0,\n term_months=12,\n extra_payments={3: \"500.00\", 6: \"500.00\"},\n )\n\n assert result[\"scheduled_payment\"] == Decimal(\"888.49\")\n assert result[\"schedule\"][0][\"interest\"] == Decimal(\"100.00\")\n assert result[\"schedule\"][0][\"balance\"] == Decimal(\"9211.51\")\n assert result[\"payoff_month\"] == 11\n assert result[\"schedule\"][-1][\"payment\"] == Decimal(\"701.22\")\n assert result[\"total_interest\"] == Decimal(\"586.12\")\n assert result[\"total_paid\"] == Decimal(\"10586.12\")\n\n for row in result[\"schedule\"]:\n print(\n f\"m={row['month']:>2} pay={row['payment']:>8} \"\n f\"int={row['interest']:>7} prin={row['principal']:>8} \"\n f\"extra={row['extra']:>7} bal={row['balance']:>9}\"\n )\n print(\"payoff month:\", result[\"payoff_month\"])\n print(\"total interest:\", result[\"total_interest\"])\n print(\"total paid:\", result[\"total_paid\"])"}], "meta": {"idx": 2467, "topic": "loan and mortgage amortization schedules", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1304, "latency_s": 72.0}} +{"prompt": [{"role": "user", "content": "A small ledger records journal entries as tuples (entry_id, description, amount) where amount is a Decimal that is positive for debits and negative for credits. Mistakes happen, and the ledger supports two correction mechanisms: a REVERSAL adds a new entry with the exact opposite amount of a previous entry (cancelling it out), while a VOID marks an entry as voided so it is excluded from the balance entirely. Write a function `net_balance(entries, voided_ids)` that takes a list of such tuples and a set of voided entry_ids, and returns the net balance as a Decimal rounded to 2 places with ROUND_HALF_UP. Entries whose ids are in voided_ids are ignored; all other entries, including reversals, contribute normally. For example, entries = [(1, 'cash sale', Decimal('120.00')), (2, 'bank fee', Decimal('-15.50')), (3, 'reversal of sale', Decimal('-120.00'))] with voided_ids = {2} yields Decimal('0.00'), since the voided fee is excluded and the sale is cancelled by its reversal."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef net_balance(entries, voided_ids):\n \"\"\"Compute the net ledger balance, excluding voided entries.\n\n entries: list of (entry_id, description, Decimal amount)\n voided_ids: set of entry_ids that are voided and excluded\n Returns: Decimal net balance rounded to 2 places, ROUND_HALF_UP.\n \"\"\"\n voided = set(voided_ids)\n total = Decimal('0')\n for entry_id, _description, amount in entries:\n if entry_id in voided:\n continue\n total += Decimal(amount)\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n\nif __name__ == '__main__':\n entries = [\n (1, 'cash sale', Decimal('120.00')),\n (2, 'bank fee', Decimal('-15.50')),\n (3, 'reversal of sale', Decimal('-120.00')),\n ]\n result = net_balance(entries, {2})\n print(result)\n assert result == Decimal('0.00')\n\n entries2 = [\n (10, 'invoice paid', Decimal('250.75')),\n (11, 'refund', Decimal('-40.20')),\n (12, 'voided duplicate', Decimal('250.75')),\n ]\n result2 = net_balance(entries2, {12})\n print(result2)\n assert result2 == Decimal('210.55')"}], "meta": {"idx": 2473, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 556, "latency_s": 4.8}} +{"prompt": [{"role": "user", "content": "You are building a small bookkeeping tool that computes VAT (value-added tax) for a journal of invoice lines and produces a balanced double-entry posting. Each invoice line has a net amount (a string like '19.99'), a VAT rate in percent given as a string (e.g. '19' or '7'), and a flag indicating whether the amount is net (VAT added on top) or gross (VAT included). For net lines, VAT = net * rate / 100, rounded half-up to 2 decimals. For gross lines, net = gross / (1 + rate/100) and VAT = gross - net, both rounded half-up to 2 decimals (compute the unrounded net first, then round once, then derive VAT as gross - rounded net so lines balance exactly). The tool must return, as a Decimal-accurate result, a dict with keys 'total_net', 'total_vat', 'total_gross' (each a Decimal rounded to 2 places), and 'lines': a list of per-line dicts with 'net', 'vat', 'gross' Decimals. All arithmetic must use Decimal with ROUND_HALF_UP; never float. Example: line ('19.99', '19', net=True) gives net=19.99, vat=3.80 (19.99*0.19=3.7981 -> 3.80), gross=23.79; line ('10.70', '7', net=False) gives gross=10.70, net=10.00, vat=0.70. Given input lines [('19.99','19',True), ('10.70','7',False)], the output totals are total_net=29.99, total_vat=4.50, total_gross=34.49."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef round2(value):\n return value.quantize(TWO, rounding=ROUND_HALF_UP)\n\n\ndef compute_vat(lines):\n \"\"\"lines: list of (amount_str, rate_str, is_net). Returns totals dict with Decimals.\"\"\"\n result_lines = []\n total_net = Decimal('0')\n total_vat = Decimal('0')\n\n for amount_str, rate_str, is_net in lines:\n amount = Decimal(amount_str)\n rate = Decimal(rate_str)\n\n if is_net:\n net = round2(amount)\n vat = round2(amount * rate / Decimal('100'))\n gross = round2(net + vat)\n else:\n gross = round2(amount)\n net_exact = amount / (Decimal('1') + rate / Decimal('100'))\n net = round2(net_exact)\n vat = round2(gross - net)\n\n result_lines.append({\n 'net': net,\n 'vat': vat,\n 'gross': gross,\n })\n total_net += net\n total_vat += vat\n\n total_gross = total_net + total_vat\n return {\n 'total_net': round2(total_net),\n 'total_vat': round2(total_vat),\n 'total_gross': round2(total_gross),\n 'lines': result_lines,\n }\n\n\nif __name__ == '__main__':\n lines = [('19.99', '19', True), ('10.70', '7', False)]\n result = compute_vat(lines)\n print('total_net =', result['total_net'])\n print('total_vat =', result['total_vat'])\n print('total_gross =', result['total_gross'])\n for i, line in enumerate(result['lines'], 1):\n print(f'line {i}: net={line[\"net\"]} vat={line[\"vat\"]} gross={line[\"gross\"]}')\n assert result['total_net'] == Decimal('29.99')\n assert result['total_vat'] == Decimal('4.50')\n assert result['total_gross'] == Decimal('34.49')\n assert result['lines'][0] == {'net': Decimal('19.99'), 'vat': Decimal('3.80'), 'gross': Decimal('23.79')}\n assert result['lines'][1] == {'net': Decimal('10.00'), 'vat': Decimal('0.70'), 'gross': Decimal('10.70')}\n print('All checks passed.')"}], "meta": {"idx": 2472, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 839, "latency_s": 13.2}} +{"prompt": [{"role": "user", "content": "You are building the tax engine for a small bookkeeping system. Given a list of invoice line items, each described by a tuple (net_amount_str, vat_rate_str, category), compute the VAT for each line using Decimal arithmetic with ROUND_HALF_UP quantization to whole cents. Some categories are 'zero-rated' (VAT always 0), 'reduced' (use the given reduced rate), and 'standard' (use the given standard rate); the vat_rate_str in the tuple is ignored for zero-rated items and must be replaced with the applicable rate for the others according to a supplied rates dictionary. Return a dictionary with keys 'lines', 'total_net', 'total_vat', and 'total_gross', where 'lines' is a list of dicts (one per input line, in order) with keys 'net', 'vat', 'gross', and 'category'. For example, with rates {'standard': '20.00', 'reduced': '5.00'} and items [('10.05', '20.00', 'standard'), ('3.33', '5.00', 'reduced'), ('7.00', '20.00', 'zero-rated')], the VAT amounts are 2.01 (10.05 * 0.20 = 2.010 -> 2.01), 0.17 (3.33 * 0.05 = 0.1665 -> 0.17), and 0.00, giving totals: net 20.38, vat 2.18, gross 22.56. Write a function compute_tax_lines(items, rates) that returns this report; totals must also be quantized to whole cents."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\n\ndef _to_cent(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef compute_tax_lines(items, rates):\n rate_map = {\n 'standard': Decimal(rates.get('standard', '0')),\n 'reduced': Decimal(rates.get('reduced', '0')),\n 'zero-rated': Decimal('0'),\n }\n lines = []\n total_net = Decimal('0')\n total_vat = Decimal('0')\n total_gross = Decimal('0')\n\n for net_str, _ignored_rate, category in items:\n net = _to_cent(Decimal(net_str))\n rate = rate_map.get(category, Decimal('0'))\n vat = _to_cent(net * rate / Decimal('100'))\n gross = _to_cent(net + vat)\n lines.append({\n 'net': net,\n 'vat': vat,\n 'gross': gross,\n 'category': category,\n })\n total_net += net\n total_vat += vat\n total_gross += gross\n\n return {\n 'lines': lines,\n 'total_net': _to_cent(total_net),\n 'total_vat': _to_cent(total_vat),\n 'total_gross': _to_cent(total_gross),\n }\n\n\nif __name__ == '__main__':\n rates = {'standard': '20.00', 'reduced': '5.00'}\n items = [\n ('10.05', '20.00', 'standard'),\n ('3.33', '5.00', 'reduced'),\n ('7.00', '20.00', 'zero-rated'),\n ]\n report = compute_tax_lines(items, rates)\n for line in report['lines']:\n print(line['category'], line['net'], line['vat'], line['gross'])\n print('TOTALS:', report['total_net'], report['total_vat'], report['total_gross'])"}], "meta": {"idx": 2456, "topic": "sales tax and VAT computation and rounding", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 712, "latency_s": 179.5}} +{"prompt": [{"role": "user", "content": "Write a function `summarize_ledger(entries)` that takes a list of ledger entries and returns a P&L summary and a balance-sheet summary. Each entry is a tuple `(date, account, debit, credit)` where debit and credit are Decimal amounts (at most one of them is non-zero). Accounts starting with 'Revenue:' count into revenue, accounts starting with 'Expense:' count into expenses, and accounts 'Cash', 'AR', 'AP', 'Equity' are balance-sheet accounts. P&L: net_income = total_revenue - total_expenses. Balance sheet: assets = sum of debit balances for 'Cash' and 'AR' (debits minus credits), liabilities = sum of credit balances for 'AP' (credits minus debits), equity = credits minus debits for 'Equity' plus net_income. Return a dict {'net_income': Decimal, 'assets': Decimal, 'liabilities': Decimal, 'equity': Decimal}. All amounts must be rounded to 2 decimal places with ROUND_HALF_UP. Example: entries = [('2024-01-01','Equity',Decimal('0'),Decimal('100.00')), ('2024-01-02','Cash',Decimal('100.00'),Decimal('0')), ('2024-01-03','Revenue:Sales',Decimal('0'),Decimal('50.255')), ('2024-01-04','Expense:Rent',Decimal('20.00'),Decimal('0'))] gives {'net_income': Decimal('30.26'), 'assets': Decimal('100.00'), 'liabilities': Decimal('0.00'), 'equity': Decimal('130.26')}. Note that the revenue of 50.255 rounds to 50.26 before subtracting expenses."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef _round2(x):\n return x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\ndef summarize_ledger(entries):\n revenue = Decimal('0')\n expenses = Decimal('0')\n assets = Decimal('0')\n liabilities = Decimal('0')\n equity = Decimal('0')\n for date, account, debit, credit in entries:\n debit = Decimal(debit)\n credit = Decimal(credit)\n if account.startswith('Revenue:'):\n revenue += credit - debit\n elif account.startswith('Expense:'):\n expenses += debit - credit\n elif account in ('Cash', 'AR'):\n assets += debit - credit\n elif account == 'AP':\n liabilities += credit - debit\n elif account == 'Equity':\n equity += credit - debit\n net_income = _round2(revenue) - _round2(expenses)\n net_income = _round2(net_income)\n assets = _round2(assets)\n liabilities = _round2(liabilities)\n equity = _round2(equity + net_income)\n return {\n 'net_income': net_income,\n 'assets': assets,\n 'liabilities': liabilities,\n 'equity': equity,\n }\n\nif __name__ == '__main__':\n from decimal import Decimal as D\n entries = [\n ('2024-01-01', 'Equity', D('0'), D('100.00')),\n ('2024-01-02', 'Cash', D('100.00'), D('0')),\n ('2024-01-03', 'Revenue:Sales', D('0'), D('50.255')),\n ('2024-01-04', 'Expense:Rent', D('20.00'), D('0')),\n ]\n print(summarize_ledger(entries))\n # {'net_income': Decimal('30.26'), 'assets': Decimal('100.00'),\n # 'liabilities': Decimal('0.00'), 'equity': Decimal('130.26')}"}], "meta": {"idx": 2471, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 761, "latency_s": 24.5}} +{"prompt": [{"role": "user", "content": "Write a function `depreciation_schedule(cost, salvage, useful_life, method, rate=None, decimals=2)` that builds a depreciation schedule for a fixed asset. `cost` and `salvage` are Decimal or string amounts, `useful_life` is a positive integer number of years, and `method` is either 'straight_line' or 'declining_balance'. For 'straight_line', each year's depreciation is (cost - salvage) / useful_life, rounded to the nearest cent with ROUND_HALF_UP, except the final year, which absorbs any accumulated rounding difference so total depreciation exactly equals cost - salvage. For 'declining_balance', each year's depreciation is the prior year's book value multiplied by `rate` (a Decimal between 0 and 1), rounded to the nearest cent; in the final year, depreciation is capped so the asset's ending book value never falls below salvage, and if book value would remain above salvage after the last year, the final year's depreciation is increased to bring book value exactly to salvage. Return a list of dictionaries, one per year, each with keys 'year' (int, starting at 1), 'depreciation' (Decimal), 'accumulated_depreciation' (Decimal), and 'book_value' (Decimal), all rounded to `decimals` places. Raise ValueError for invalid inputs (non-positive useful_life, rate outside (0,1) for declining balance, salvage > cost, or unknown method). Example: cost='10000.00', salvage='1000.00', useful_life=5, method='straight_line' gives yearly depreciation of 1800.00 for years 1-5, with book values 8200.00, 6400.00, 4600.00, 2800.00, 1000.00 and accumulated depreciation 1800.00, 3600.00, 5400.00, 7200.00, 9000.00. Example: cost='5000.00', salvage='500.00', useful_life=3, method='declining_balance', rate=Decimal('0.4') gives year 1 depreciation 2000.00 (book 3000.00), year 2 depreciation 1200.00 (book 1800.00), and year 3 depreciation 1300.00 (book 500.00), because the final year is adjusted to land exactly on salvage."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef depreciation_schedule(cost, salvage, useful_life, method, rate=None, decimals=2):\n cost = Decimal(str(cost))\n salvage = Decimal(str(salvage))\n if useful_life <= 0:\n raise ValueError('useful_life must be a positive integer')\n if salvage > cost:\n raise ValueError('salvage cannot exceed cost')\n if method not in ('straight_line', 'declining_balance'):\n raise ValueError('unknown method: %r' % (method,))\n\n quant = Decimal(1).scaleb(-decimals) # e.g. 0.01\n\n def q(x):\n return x.quantize(quant, rounding=ROUND_HALF_UP)\n\n schedule = []\n book = q(cost)\n salvage_q = q(salvage)\n total_depreciable = q(cost - salvage)\n\n if method == 'straight_line':\n annual = q((cost - salvage) / Decimal(useful_life))\n accumulated = Decimal('0')\n for year in range(1, useful_life + 1):\n if year < useful_life:\n dep = annual\n else:\n dep = total_depreciable - accumulated\n accumulated = q(accumulated + dep)\n book = q(book - dep)\n schedule.append({\n 'year': year,\n 'depreciation': q(dep),\n 'accumulated_depreciation': accumulated,\n 'book_value': book,\n })\n else: # declining_balance\n if rate is None:\n raise ValueError('rate is required for declining_balance')\n rate = Decimal(str(rate))\n if rate <= 0 or rate >= 1:\n raise ValueError('rate must be between 0 and 1 (exclusive)')\n accumulated = Decimal('0')\n for year in range(1, useful_life + 1):\n proposed = q(book * rate)\n if year == useful_life:\n # Final year: bring book value exactly to salvage.\n dep = book - salvage_q\n if dep < 0:\n dep = Decimal('0')\n else:\n dep = proposed\n # Never let book value drop below salvage early.\n if book - dep < salvage_q:\n dep = book - salvage_q\n accumulated = q(accumulated + dep)\n book = q(book - dep)\n schedule.append({\n 'year': year,\n 'depreciation': q(dep),\n 'accumulated_depreciation': accumulated,\n 'book_value': book,\n })\n\n return schedule\n\n\nif __name__ == '__main__':\n for row in depreciation_schedule('10000.00', '1000.00', 5, 'straight_line'):\n print(row)\n print()\n for row in depreciation_schedule('5000.00', '500.00', 3, 'declining_balance', rate='0.4'):\n print(row)"}], "meta": {"idx": 2466, "topic": "depreciation schedules (straight-line, declining balance)", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1178, "latency_s": 106.7}} +{"prompt": [{"role": "user", "content": "Write a function `aging_report(invoices)` that produces an accounts receivable/payable aging report. Each invoice is a dict with keys 'id' (string), 'amount' (Decimal or string representing money), and 'days_outstanding' (int). The function must bucket each invoice into one of four aging buckets: '0-30' if days_outstanding <= 30, '31-60' if 31-60, '61-90' if 61-90, and '90+' if greater than 90. It must return a dict mapping each bucket name to the total amount owed in that bucket, using Decimal arithmetic with ROUND_HALF_UP quantization to 2 decimal places, and all four buckets must always appear in the result (with Decimal('0.00') if empty). For example, given invoices [{'id': 'A1', 'amount': '150.00', 'days_outstanding': 12}, {'id': 'A2', 'amount': '99.995', 'days_outstanding': 45}, {'id': 'A3', 'amount': '200.00', 'days_outstanding': 95}], the function returns {'0-30': Decimal('150.00'), '31-60': Decimal('100.00'), '61-90': Decimal('0.00'), '90+': Decimal('200.00')}. Any invoice with a negative amount should raise a ValueError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nBUCKETS = ['0-30', '31-60', '61-90', '90+']\nTWO_PLACES = Decimal('0.01')\n\ndef aging_report(invoices):\n totals = {b: Decimal('0.00') for b in BUCKETS}\n for inv in invoices:\n amount = Decimal(str(inv['amount']))\n if amount < 0:\n raise ValueError(\"Invoice amount must be non-negative: {}\".format(inv.get('id')))\n days = inv['days_outstanding']\n if days <= 30:\n bucket = '0-30'\n elif days <= 60:\n bucket = '31-60'\n elif days <= 90:\n bucket = '61-90'\n else:\n bucket = '90+'\n totals[bucket] += amount\n for b in BUCKETS:\n totals[b] = totals[b].quantize(TWO_PLACES, rounding=ROUND_HALF_UP)\n return totals\n\nif __name__ == '__main__':\n invoices = [\n {'id': 'A1', 'amount': '150.00', 'days_outstanding': 12},\n {'id': 'A2', 'amount': '99.995', 'days_outstanding': 45},\n {'id': 'A3', 'amount': '200.00', 'days_outstanding': 95},\n ]\n print(aging_report(invoices))"}], "meta": {"idx": 2477, "topic": "accounts receivable and payable aging reports", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 541, "latency_s": 15.3}} +{"prompt": [{"role": "user", "content": "You are building a small accounts-recurring feature for a bookkeeping system. You must generate ledger postings for recurring monthly charges defined by a schedule, and compute the resulting ledger balances. Input: a start date, an end date (inclusive), a monthly amount (Decimal, cents precision), a day-of-month for posting (1-28, so no month-length issues), and a posting direction ('debit' or 'credit'). Rules: generate one posting on the given day of each month between start and end inclusive (if the start date's day is on or before the posting day, the first month is the start month, otherwise the next month; similarly, if the end date's day is before the posting day, the last month is the month before the end month). Each posting amount must be rounded to cents with ROUND_HALF_UP. Additionally, apply a yearly cap: total postings per calendar year must not exceed 12 postings; skip any posting that would exceed this. Output: the list of postings as (date, direction, amount) tuples in chronological order, plus two totals: total_debits and total_credits as Decimals. Example: start=2024-11-15, end=2025-03-10, amount=Decimal('99.995'), day=20, direction='debit' gives postings on 2024-11-20, 2024-12-20, 2025-01-20, 2025-02-20, 2025-03-20? No \u2014 March 20 is after the end date 2025-03-10, so the last posting is 2025-02-20. Amounts round to 100.00 each, so total_debits = 400.00 and total_credits = 0.00. Write a function generate_recurring_postings(start, end, amount, day, direction) that returns (postings, total_debits, total_credits)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\nCENT = Decimal('0.01')\n\n\ndef add_months(d, months):\n total = d.year * 12 + (d.month - 1) + months\n year, month = divmod(total, 12)\n month += 1\n return date(year, month, min(d.day, 28))\n\n\ndef generate_recurring_postings(start, end, amount, day, direction):\n if not (1 <= day <= 28):\n raise ValueError('day must be 1-28')\n if direction not in ('debit', 'credit'):\n raise ValueError(\"direction must be 'debit' or 'credit'\")\n\n # First candidate month\n if start.day <= day:\n first = date(start.year, start.month, day)\n else:\n first = add_months(date(start.year, start.month, day), 1)\n\n # Last candidate month\n if end.day >= day:\n last = date(end.year, end.month, day)\n else:\n last = add_months(date(end.year, end.month, day), -1)\n\n amount = Decimal(amount).quantize(CENT, rounding=ROUND_HALF_UP)\n\n postings = []\n per_year = {}\n current = first\n while current <= last:\n year = current.year\n if per_year.get(year, 0) < 12:\n per_year[year] = per_year.get(year, 0) + 1\n postings.append((current, direction, amount))\n current = add_months(current, 1)\n\n total_debits = sum((p[2] for p in postings if p[1] == 'debit'), Decimal('0.00'))\n total_credits = sum((p[2] for p in postings if p[1] == 'credit'), Decimal('0.00'))\n return postings, total_debits, total_credits\n\n\nif __name__ == '__main__':\n postings, dr, cr = generate_recurring_postings(\n date(2024, 11, 15), date(2025, 3, 10), Decimal('99.995'), 20, 'debit')\n for p in postings:\n print(p)\n print('total_debits:', dr)\n print('total_credits:', cr)\n # Expected: 4 postings (2024-11-20 .. 2025-02-20), total_debits 400.00, total_credits 0.00\n assert len(postings) == 4\n assert postings[0] == (date(2024, 11, 20), 'debit', Decimal('100.00'))\n assert postings[-1] == (date(2025, 2, 20), 'debit', Decimal('100.00'))\n assert dr == Decimal('400.00') and cr == Decimal('0.00')\n print('OK')"}], "meta": {"idx": 2476, "topic": "recurring and calendar-based postings", "difficulty": "medium", "provider": "novita", "in_tokens": 197, "out_tokens": 1096, "latency_s": 11.2}} +{"prompt": [{"role": "user", "content": "A small business needs to allocate a quarterly expense across its departments proportionally to their headcounts, using banker's rounding (ROUND_HALF_EVEN) to the nearest cent. Write a function `allocate(total_cents, headcounts)` that takes a non-negative integer total in cents and a list of positive integer headcounts, and returns a list of integer cent amounts, one per department. The sum of the returned amounts must equal `total_cents` exactly, and each amount must equal the correctly rounded share computed with Decimal arithmetic, with any rounding residue distributed by adjusting the department(s) whose rounded share differs most from the exact share (adding 1 cent at a time to the department with the largest negative rounding error, or subtracting 1 cent from the department with the largest positive rounding error). For example, allocate(1000, [1, 1, 1]) should return [334, 333, 333] because each exact share is 333.333... cents, banker's rounding gives 333 for each, and the missing 1 cent goes to the first department. Use only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_EVEN\n\ndef allocate(total_cents, headcounts):\n if total_cents < 0:\n raise ValueError('total_cents must be non-negative')\n if not headcounts or any(h <= 0 for h in headcounts):\n raise ValueError('headcounts must be positive integers')\n total_heads = sum(headcounts)\n total = Decimal(total_cents)\n exact = [total * Decimal(h) / Decimal(total_heads) for h in headcounts]\n cents = [int(e.quantize(Decimal('1'), rounding=ROUND_HALF_EVEN)) for e in exact]\n diff = total_cents - sum(cents)\n step = 1 if diff > 0 else -1\n for _ in range(abs(diff)):\n errors = [exact[i] - Decimal(cents[i]) for i in range(len(headcounts))]\n if step == 1:\n idx = max(range(len(errors)), key=lambda i: errors[i])\n else:\n idx = min(range(len(errors)), key=lambda i: errors[i])\n cents[idx] += step\n assert sum(cents) == total_cents\n return cents\n\nif __name__ == '__main__':\n print(allocate(1000, [1, 1, 1]))\n print(allocate(100, [3, 3, 4]))\n print(allocate(505, [2, 5]))"}], "meta": {"idx": 2479, "topic": "currency rounding rules with the Decimal type", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 553, "latency_s": 13.7}} +{"prompt": [{"role": "user", "content": "You are building an immutable audit trail for a petty-cash ledger. Each entry records an account code (string), a description (string), and an amount (Decimal, positive for debit, negative for credit). Entries must be stored in an append-only log: once appended, an entry can never be modified or deleted. To correct mistakes, you instead append a reversal entry that references the original entry's sequence number and contains the negated amount. Implement a class AuditLedger with: append(account, description, amount) -> seq (an integer sequence number starting at 1); reverse(seq, reason) -> seq of the reversal entry; balance(account=None) -> Decimal total (all accounts if None); and entries() -> list of dicts in insertion order (keys: seq, account, description, amount, reversed_seq which is None unless it is a reversal entry). Any attempt to mutate or delete an existing entry (e.g., calling a method like edit or delete, if provided) must raise TypeError. Monetary amounts must be handled with Decimal and rounded to 2 decimal places using ROUND_HALF_UP on append. Example: ledger = AuditLedger(); s1 = ledger.append('1001', 'Cash box start', Decimal('50.00')); s2 = ledger.append('5001', 'Office supplies', Decimal('-12.345')); assert s1 == 1 and s2 == 2; assert ledger.balance() == Decimal('37.66') because -12.345 rounds to -12.35 (ROUND_HALF_UP on the magnitude, i.e., away from zero); assert ledger.balance('1001') == Decimal('50.00'). Then r = ledger.reverse(s2, 'wrong vendor') gives seq 3, ledger.balance() returns Decimal('50.00'), and entries()[2]['reversed_seq'] == 2."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\nclass AuditLedger:\n \"\"\"Append-only audit ledger for bookkeeping entries.\"\"\"\n\n def __init__(self):\n self._entries = []\n self._next_seq = 1\n\n @staticmethod\n def _round_half_up(value):\n # ROUND_HALF_UP in Python's decimal rounds away from zero on ties,\n # which matches the spec (magnitude-based half-up).\n return value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\n def append(self, account, description, amount):\n amount = self._round_half_up(Decimal(str(amount)))\n entry = {\n 'seq': self._next_seq,\n 'account': account,\n 'description': description,\n 'amount': amount,\n 'reversed_seq': None,\n }\n self._entries.append(entry)\n self._next_seq += 1\n return entry['seq']\n\n def reverse(self, seq, reason):\n if not isinstance(seq, int):\n raise TypeError('sequence number must be an integer')\n target = None\n for e in self._entries:\n if e['seq'] == seq:\n target = e\n break\n if target is None:\n raise ValueError('no entry with sequence number %r' % (seq,))\n if target['reversed_seq'] is not None:\n raise ValueError('entry %d is itself a reversal and cannot be reversed' % seq)\n for e in self._entries:\n if e.get('reversed_seq') == seq:\n raise ValueError('entry %d has already been reversed' % seq)\n rev_seq = self.append(\n target['account'],\n 'REVERSAL of #%d: %s' % (seq, reason),\n -target['amount'],\n )\n self._entries[-1]['reversed_seq'] = seq\n return rev_seq\n\n def balance(self, account=None):\n total = Decimal('0.00')\n for e in self._entries:\n if account is None or e['account'] == account:\n total += e['amount']\n return self._round_half_up(total)\n\n def entries(self):\n # Return copies so external code cannot mutate the log through them.\n return [dict(e) for e in self._entries]\n\n # Immutability guards: the log is append-only.\n def __setattr__(self, name, value):\n if name in ('_entries', '_next_seq'):\n if not hasattr(self, name):\n return object.__setattr__(self, name, value)\n if name == '_entries' and id(value) != id(getattr(self, name)):\n raise TypeError('audit log is append-only: cannot rebind entries')\n return object.__setattr__(self, name, value)\n raise TypeError('audit log is immutable: cannot set attribute %r' % name)\n\n def __delattr__(self, name):\n raise TypeError('audit log is append-only: cannot delete %r' % name)\n\n def edit(self, *args, **kwargs):\n raise TypeError('audit log is append-only: entries cannot be edited')\n\n def delete(self, *args, **kwargs):\n raise TypeError('audit log is append-only: entries cannot be deleted')\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n ledger = AuditLedger()\n s1 = ledger.append('1001', 'Cash box start', Decimal('50.00'))\n s2 = ledger.append('5001', 'Office supplies', Decimal('-12.345'))\n assert s1 == 1 and s2 == 2\n assert ledger.balance() == Decimal('37.66')\n assert ledger.balance('1001') == Decimal('50.00')\n r = ledger.reverse(s2, 'wrong vendor')\n assert r == 3\n assert ledger.balance() == Decimal('50.00')\n assert ledger.entries()[2]['reversed_seq'] == 2\n assert ledger.entries()[2]['amount'] == Decimal('12.35')\n try:\n ledger.delete(1)\n except TypeError:\n pass\n else:\n raise AssertionError('delete should raise TypeError')\n print('all checks passed')"}], "meta": {"idx": 2480, "topic": "audit trails and immutable entry logs", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1377, "latency_s": 11.4}} +{"prompt": [{"role": "user", "content": "Write a function `build_trial_balance(entries)` that constructs a trial balance from a list of journal entries and detects imbalance. Each entry is a tuple `(account, debit, credit)` where debit and credit are strings representing monetary amounts (e.g. '150.00'); at most one of the two amounts per entry is non-zero. The function must use `decimal.Decimal` for exact arithmetic and return a tuple `(debit_total, credit_total, is_balanced, balances)` where `debit_total` and `credit_total` are Decimals quantized to 2 decimal places, `is_balanced` is a bool that is True when the two totals are exactly equal, and `balances` is a dict mapping each account to its net balance (debits minus credits), also as Decimals quantized to 2 places. For example, given entries `[('Cash', '100.00', '0'), ('Revenue', '0', '100.00')]`, the function returns `(Decimal('100.00'), Decimal('100.00'), True, {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')})`. If the debits and credits do not match, `is_balanced` must be False."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\n\n\ndef build_trial_balance(entries):\n \"\"\"Build a trial balance from journal entries and detect imbalance.\n\n Args:\n entries: list of (account, debit_str, credit_str) tuples.\n\n Returns:\n (debit_total, credit_total, is_balanced, balances) where the totals\n and per-account net balances are Decimals quantized to 2 places.\n \"\"\"\n cents = Decimal('0.01')\n debit_total = Decimal('0')\n credit_total = Decimal('0')\n balances = {}\n\n for account, debit_str, credit_str in entries:\n debit = Decimal(debit_str)\n credit = Decimal(credit_str)\n debit_total += debit\n credit_total += credit\n balances[account] = balances.get(account, Decimal('0')) + debit - credit\n\n debit_total = debit_total.quantize(cents)\n credit_total = credit_total.quantize(cents)\n balances = {acc: bal.quantize(cents) for acc, bal in balances.items()}\n\n return debit_total, credit_total, debit_total == credit_total, balances\n\n\nif __name__ == '__main__':\n entries = [\n ('Cash', '100.00', '0'),\n ('Revenue', '0', '100.00'),\n ]\n result = build_trial_balance(entries)\n print(result)\n assert result == (\n Decimal('100.00'),\n Decimal('100.00'),\n True,\n {'Cash': Decimal('100.00'), 'Revenue': Decimal('-100.00')},\n )\n\n unbalanced = [\n ('Cash', '250.50', '0'),\n ('Supplies', '30.25', '0'),\n ('Revenue', '0', '280.75'),\n ('Equipment', '10.00', '0'),\n ]\n dt, ct, ok, bals = build_trial_balance(unbalanced)\n print(dt, ct, ok, bals)\n assert dt == Decimal('290.75')\n assert ct == Decimal('280.75')\n assert ok is False\n assert bals['Equipment'] == Decimal('10.00')\n print('All checks passed.')"}], "meta": {"idx": 2481, "topic": "trial balance construction and imbalance detection", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 723, "latency_s": 5.3}} +{"prompt": [{"role": "user", "content": "Implement a function amortize(principal, annual_rate, payments) that simulates a loan ledger using the Decimal type throughout, with all monetary amounts rounded half-up to cents. Each period, interest accrues on the current balance at monthly_rate = annual_rate/12; the period's payment is applied first to interest, then to principal. If the payment is smaller than the accrued interest, the unpaid interest is capitalized (added to the balance) and no principal is repaid; if the payment exceeds the payoff amount, only the payoff amount is applied and the loan closes. If the payments list runs out while the balance is positive, one final auto-payoff entry must close the loan with payment = interest + balance. The function returns a dict with keys 'entries' (a list of per-period dicts with keys period, interest, payment, applied_interest, applied_principal, capitalized, ending_balance), 'total_interest', and 'total_paid', and raises ValueError for a non-positive principal, a negative rate, or any non-positive payment. Example: amortize(Decimal('1000.00'), Decimal('0.12'), [Decimal('50.00'), Decimal('200.00'), Decimal('300.00')]) produces ending balances 960.00, 769.60, 477.30, then a final auto-payoff entry with interest 4.77 and payment 482.07, giving total_interest 32.07 and total_paid 1032.07; as a capitalization check, a single payment of 5.00 on 1000.00 at 1% monthly yields interest 10.00, applied_interest 5.00, capitalized 5.00, and ending_balance 1005.00."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENTS = Decimal(\"0.01\")\n\n\ndef _cents(value):\n \"\"\"Round a Decimal to cents using half-up rounding.\"\"\"\n return value.quantize(CENTS, rounding=ROUND_HALF_UP)\n\n\ndef amortize(principal, annual_rate, payments):\n \"\"\"\n Simulate a loan ledger.\n\n principal: positive Decimal, initial loan amount.\n annual_rate: non-negative Decimal, nominal annual interest rate\n (e.g. Decimal('0.12') for 12%).\n payments: list of positive Decimals, one payment per period.\n\n Rules:\n - monthly_rate = annual_rate / 12; interest for a period is\n round_half_up(balance * monthly_rate).\n - A payment is applied first to interest, then to principal.\n - If payment < interest, the unpaid interest is capitalized\n (added to the balance) and no principal is repaid.\n - If payment >= payoff (interest + balance), only the payoff\n amount is applied and the loan closes.\n - If the payments list is exhausted while the balance is\n positive, one final auto-payoff entry closes the loan.\n\n Returns a dict with 'entries', 'total_interest', 'total_paid'.\n \"\"\"\n principal = Decimal(principal)\n annual_rate = Decimal(annual_rate)\n payments = [Decimal(p) for p in payments]\n\n if principal <= 0:\n raise ValueError(\"principal must be positive\")\n if annual_rate < 0:\n raise ValueError(\"annual_rate must be non-negative\")\n if not payments or any(p <= 0 for p in payments):\n raise ValueError(\"all payments must be positive\")\n\n monthly_rate = annual_rate / Decimal(12)\n balance = _cents(principal)\n entries = []\n total_interest = Decimal(\"0.00\")\n total_paid = Decimal(\"0.00\")\n period = 0\n\n def apply_payment(payment):\n nonlocal balance, total_interest, total_paid, period\n interest = _cents(balance * monthly_rate)\n payoff = _cents(balance + interest)\n actual_payment = min(_cents(payment), payoff)\n\n applied_interest = min(actual_payment, interest)\n applied_principal = actual_payment - applied_interest\n capitalized = interest - applied_interest\n\n balance = _cents(balance + capitalized - applied_principal)\n\n total_interest = _cents(total_interest + interest)\n total_paid = _cents(total_paid + actual_payment)\n\n period += 1\n entries.append({\n \"period\": period,\n \"interest\": interest,\n \"payment\": actual_payment,\n \"applied_interest\": applied_interest,\n \"applied_principal\": applied_principal,\n \"capitalized\": capitalized,\n \"ending_balance\": balance,\n })\n\n for payment in payments:\n if balance <= 0:\n break\n apply_payment(payment)\n\n if balance > 0:\n # Auto-payoff: interest accrues once more, then the loan closes.\n interest = _cents(balance * monthly_rate)\n apply_payment(balance + interest)\n\n return {\n \"entries\": entries,\n \"total_interest\": total_interest,\n \"total_paid\": total_paid,\n }\n\n\nif __name__ == \"__main__\":\n # Worked example from the statement.\n result = amortize(\n Decimal(\"1000.00\"),\n Decimal(\"0.12\"),\n [Decimal(\"50.00\"), Decimal(\"200.00\"), Decimal(\"300.00\")],\n )\n expected_balances = [\n Decimal(\"960.00\"),\n Decimal(\"769.60\"),\n Decimal(\"477.30\"),\n Decimal(\"0.00\"),\n ]\n assert [e[\"ending_balance\"] for e in result[\"entries\"]] == expected_balances\n assert result[\"entries\"][3][\"interest\"] == Decimal(\"4.77\")\n assert result[\"entries\"][3][\"payment\"] == Decimal(\"482.07\")\n assert result[\"total_interest\"] == Decimal(\"32.07\")\n assert result[\"total_paid\"] == Decimal(\"1032.07\")\n\n # Capitalization check: payment smaller than accrued interest.\n cap = amortize(Decimal(\"1000.00\"), Decimal(\"0.12\"), [Decimal(\"5.00\")])\n first = cap[\"entries\"][0]\n assert first[\"interest\"] == Decimal(\"10.00\")\n assert first[\"applied_interest\"] == Decimal(\"5.00\")\n assert first[\"capitalized\"] == Decimal(\"5.00\")\n assert first[\"applied_principal\"] == Decimal(\"0.00\")\n assert first[\"ending_balance\"] == Decimal(\"1005.00\")\n\n # Overpayment is capped at the payoff amount.\n over = amortize(Decimal(\"100.00\"), Decimal(\"0.12\"), [Decimal(\"500.00\")])\n assert over[\"entries\"][0][\"payment\"] == Decimal(\"101.00\")\n assert over[\"entries\"][0][\"ending_balance\"] == Decimal(\"0.00\")\n assert len(over[\"entries\"]) == 1\n\n # Invalid inputs raise ValueError.\n for bad in (\n lambda: amortize(Decimal(\"0\"), Decimal(\"0.12\"), [Decimal(\"10\")]),\n lambda: amortize(Decimal(\"10\"), Decimal(\"-0.1\"), [Decimal(\"1\")]),\n lambda: amortize(Decimal(\"10\"), Decimal(\"0.12\"), [Decimal(\"0\")]),\n ):\n try:\n bad()\n raise AssertionError(\"expected ValueError\")\n except ValueError:\n pass\n\n print(\"All checks passed.\")\n for e in result[\"entries\"]:\n print(e)\n print(\"total_interest:\", result[\"total_interest\"])\n print(\"total_paid:\", result[\"total_paid\"])"}], "meta": {"idx": 2475, "topic": "interest calculation and payment schedules", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1735, "latency_s": 39.9}} +{"prompt": [{"role": "user", "content": "You maintain a chart of accounts as a dict mapping account codes (strings like '5000') to account names, and a list of expense line items, each a dict with keys 'account', 'description', and 'amount' (a string like '123.45'). Write a function `summarize_expenses(chart, entries)` that returns a dict mapping each account code appearing in the entries to a Decimal total rounded to exactly 2 decimal places (ROUND_HALF_UP). If an entry references an account code not in the chart, raise a ValueError with the message 'unknown account: CODE'. Amounts must be parsed with Decimal, never float, and invalid amount strings (unparseable by Decimal) must raise a ValueError with the message 'invalid amount: AMOUNT'. Example: chart = {'5000': 'Office Supplies', '6100': 'Travel'}; entries = [{'account': '5000', 'description': 'paper', 'amount': '10.10'}, {'account': '5000', 'description': 'pens', 'amount': '5.55'}, {'account': '6100', 'description': 'airfare', 'amount': '250.00'}] should return {'5000': Decimal('15.65'), '6100': Decimal('250.00')}."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, InvalidOperation\n\n\ndef summarize_expenses(chart, entries):\n totals = {}\n for entry in entries:\n code = entry['account']\n if code not in chart:\n raise ValueError('unknown account: ' + str(code))\n try:\n amount = Decimal(entry['amount'])\n except (InvalidOperation, TypeError):\n raise ValueError('invalid amount: ' + str(entry['amount']))\n totals[code] = totals.get(code, Decimal('0')) + amount\n return {code: total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n for code, total in totals.items()}\n\n\nif __name__ == '__main__':\n chart = {'5000': 'Office Supplies', '6100': 'Travel'}\n entries = [\n {'account': '5000', 'description': 'paper', 'amount': '10.10'},\n {'account': '5000', 'description': 'pens', 'amount': '5.55'},\n {'account': '6100', 'description': 'airfare', 'amount': '250.00'},\n ]\n result = summarize_expenses(chart, entries)\n assert result == {'5000': Decimal('15.65'), '6100': Decimal('250.00')}\n print(result)"}], "meta": {"idx": 2484, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 552, "latency_s": 7.5}} +{"prompt": [{"role": "user", "content": "You maintain a simple general ledger where every transaction is a list of lines, each with an account name and a signed Decimal amount. A transaction is valid only if its lines sum to exactly zero. Your job is to post transactions, correcting entries, reversals, and voided transactions. Implement a LedgerProcessor class with methods: post(txn_id, lines) which raises ValueError if txn_id already exists or the lines do not sum to zero (round to 2 decimal places with ROUND_HALF_UP when checking); reverse(txn_id, reversal_id) which creates a new transaction (reversal_id) with the same lines negated, raising ValueError if txn_id doesn't exist or reversal_id is taken; void(txn_id) which marks a transaction voided so its lines no longer count toward balances, raising ValueError if it doesn't exist or is already voided; and balance(account) which returns the net Decimal sum (rounded to 2 places, ROUND_HALF_UP) of all non-voided posted and reversal lines for that account. Example: post('t1', [('cash', Decimal('100.00')), ('revenue', Decimal('-100.00'))]) then balance('cash') is Decimal('100.00'); reverse('t1','r1') then balance('cash') is Decimal('0.00'); void('t1') leaves balance('cash') at Decimal('0.00') since the reversal is still active."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _round2(x):\n return x.quantize(TWO, rounding=ROUND_HALF_UP)\n\nclass LedgerProcessor:\n def __init__(self):\n self._txns = {} # id -> dict(lines, voided)\n\n def post(self, txn_id, lines):\n if txn_id in self._txns:\n raise ValueError(f'transaction {txn_id} already exists')\n total = sum((Decimal(a) for _, a in lines), Decimal('0'))\n if _round2(total) != Decimal('0.00'):\n raise ValueError(f'transaction {txn_id} does not balance: {total}')\n self._txns[txn_id] = {'lines': [(acct, Decimal(amt)) for acct, amt in lines], 'voided': False}\n\n def reverse(self, txn_id, reversal_id):\n if txn_id not in self._txns:\n raise ValueError(f'transaction {txn_id} does not exist')\n if reversal_id in self._txns:\n raise ValueError(f'transaction {reversal_id} already exists')\n original = self._txns[txn_id]['lines']\n reversed_lines = [(acct, -amt) for acct, amt in original]\n self._txns[reversal_id] = {'lines': reversed_lines, 'voided': False}\n\n def void(self, txn_id):\n if txn_id not in self._txns:\n raise ValueError(f'transaction {txn_id} does not exist')\n if self._txns[txn_id]['voided']:\n raise ValueError(f'transaction {txn_id} is already voided')\n self._txns[txn_id]['voided'] = True\n\n def balance(self, account):\n total = Decimal('0')\n for txn in self._txns.values():\n if txn['voided']:\n continue\n for acct, amt in txn['lines']:\n if acct == account:\n total += amt\n return _round2(total)\n\nif __name__ == '__main__':\n from decimal import Decimal\n lp = LedgerProcessor()\n lp.post('t1', [('cash', Decimal('100.00')), ('revenue', Decimal('-100.00'))])\n assert lp.balance('cash') == Decimal('100.00')\n lp.reverse('t1', 'r1')\n assert lp.balance('cash') == Decimal('0.00')\n lp.void('t1')\n assert lp.balance('cash') == Decimal('0.00')\n assert lp.balance('revenue') == Decimal('100.00')\n print('all checks passed')"}], "meta": {"idx": 2486, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 875, "latency_s": 13.4}} +{"prompt": [{"role": "user", "content": "Implement a general ledger with T-account support using Python's Decimal for exact money arithmetic. Each transaction posts lines of (account, debit, credit) to a ledger; debits and credits in a transaction must balance or the transaction is rejected. After posting, compute each account's balance in 'normal balance' form: for asset/expense accounts (normal debit) the balance is total debits minus total credits; for liability/revenue/equity accounts (normal credit) it is total credits minus total debits. Balances of half a cent must round half-up to the nearest cent. Provide a function `post_and_report(transactions, account_types)` that takes a list of transactions (each a list of (account, debit, credit) tuples of Decimal) and a dict mapping account name to 'debit' or 'credit' normal balance, and returns a dict mapping account name to its Decimal balance, raising ValueError on an unbalanced transaction. Example: transactions = [[('Cash', Decimal('100.00'), 0), ('Revenue', 0, Decimal('100.00'))]] with account_types = {'Cash': 'debit', 'Revenue': 'credit'} must return {'Cash': Decimal('100.00'), 'Revenue': Decimal('100.00')}. If instead a second transaction [('Rent Expense', Decimal('30.00'), 0), ('Cash', 0, Decimal('20.00'))] were included, it must raise ValueError because its debits (30.00) do not equal its credits (20.00)."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef post_and_report(transactions, account_types):\n \"\"\"Post transactions to a T-account ledger and return account balances.\n\n transactions: list of transactions; each transaction is a list of\n (account, debit, credit) tuples with Decimal amounts.\n account_types: dict mapping account name to 'debit' or 'credit'\n (its normal balance side).\n Returns dict mapping account name to Decimal balance expressed\n in the account's normal-balance form, rounded half-up to cents.\n Raises ValueError if a transaction's debits != credits.\n \"\"\"\n CENT = Decimal('0.01')\n debits = {}\n credits = {}\n\n for txn in transactions:\n total_dr = Decimal('0')\n total_cr = Decimal('0')\n for account, dr, cr in txn:\n dr = Decimal(dr)\n cr = Decimal(cr)\n if dr < 0 or cr < 0:\n raise ValueError('negative amount not allowed')\n total_dr += dr\n total_cr += cr\n debits[account] = debits.get(account, Decimal('0')) + dr\n credits[account] = credits.get(account, Decimal('0')) + cr\n if total_dr != total_cr:\n raise ValueError(\n 'unbalanced transaction: debits %s != credits %s'\n % (total_dr, total_cr)\n )\n\n balances = {}\n for account in set(debits) | set(credits):\n normal = account_types.get(account)\n if normal is None:\n raise ValueError('unknown account type for %r' % account)\n if normal == 'debit':\n raw = debits.get(account, Decimal('0')) - credits.get(account, Decimal('0'))\n elif normal == 'credit':\n raw = credits.get(account, Decimal('0')) - debits.get(account, Decimal('0'))\n else:\n raise ValueError('invalid normal balance %r for %r' % (normal, account))\n balances[account] = raw.quantize(CENT, rounding=ROUND_HALF_UP)\n return balances\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n txns = [\n [('Cash', Decimal('100.00'), Decimal('0')),\n ('Revenue', Decimal('0'), Decimal('100.00'))],\n ]\n types = {'Cash': 'debit', 'Revenue': 'credit'}\n print(post_and_report(txns, types))\n # -> {'Cash': Decimal('100.00'), 'Revenue': Decimal('100.00')}\n\n bad = txns + [[('Rent Expense', Decimal('30.00'), Decimal('0')),\n ('Cash', Decimal('0'), Decimal('20.00'))]]\n try:\n post_and_report(bad, types)\n except ValueError as e:\n print('Rejected:', e)"}], "meta": {"idx": 2482, "topic": "general ledger and T-account operations", "difficulty": "medium", "provider": "novita", "in_tokens": 198, "out_tokens": 1003, "latency_s": 10.9}} +{"prompt": [{"role": "user", "content": "At period end, a small business must post closing entries to zero out its temporary accounts (revenue and expense accounts) into a single 'Income Summary' account, and then close Income Summary into the capital account. Write a function `post_closing_entries(ledger)` that takes a dictionary mapping account names to Decimal balances, where revenue accounts (names starting with 'Revenue:') have credit balances given as positive numbers, and expense accounts (names starting with 'Expense:') have debit balances given as positive numbers. The function should return a new dictionary where every temporary account is set to Decimal('0.00'), an 'Income Summary' account holds the net income (revenues minus expenses, rounded to cents, Decimal('0.00') if zero), and a 'Capital' account is created (or updated by adding net income to any existing 'Capital' balance). Non-temporary accounts other than 'Capital' and 'Income Summary' should be carried over unchanged. For example, given {'Revenue: Sales': Decimal('1200.50'), 'Expense: Rent': Decimal('400.25'), 'Cash': Decimal('800.00')}, the result should have 'Income Summary' equal to Decimal('800.25') and 'Capital' equal to Decimal('800.25'), with both temporary accounts zeroed and 'Cash' unchanged. Use Decimal arithmetic with ROUND_HALF_UP rounding to cents throughout."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef post_closing_entries(ledger):\n \"\"\"Close temporary accounts into Income Summary, then into Capital.\"\"\"\n CENT = Decimal('0.01')\n\n def to_cents(value):\n return value.quantize(CENT, rounding=ROUND_HALF_UP)\n\n revenues = sum(\n (to_cents(v) for k, v in ledger.items() if k.startswith('Revenue:')),\n Decimal('0.00'),\n )\n expenses = sum(\n (to_cents(v) for k, v in ledger.items() if k.startswith('Expense:')),\n Decimal('0.00'),\n )\n\n net_income = to_cents(revenues - expenses)\n\n result = {}\n for account, balance in ledger.items():\n if account.startswith('Revenue:') or account.startswith('Expense:'):\n result[account] = Decimal('0.00')\n else:\n result[account] = to_cents(balance)\n\n result['Income Summary'] = net_income\n result['Capital'] = to_cents(\n result.get('Capital', Decimal('0.00')) + net_income\n )\n\n return result\n\n\nif __name__ == '__main__':\n from decimal import Decimal\n ledger = {\n 'Revenue: Sales': Decimal('1200.50'),\n 'Expense: Rent': Decimal('400.25'),\n 'Cash': Decimal('800.00'),\n }\n closed = post_closing_entries(ledger)\n print(closed)\n assert closed['Revenue: Sales'] == Decimal('0.00')\n assert closed['Expense: Rent'] == Decimal('0.00')\n assert closed['Income Summary'] == Decimal('800.25')\n assert closed['Capital'] == Decimal('800.25')\n assert closed['Cash'] == Decimal('800.00')\n print('All checks passed.')"}], "meta": {"idx": 2483, "topic": "period-end closing entries and routines", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 738, "latency_s": 27.4}} +{"prompt": [{"role": "user", "content": "Write a function `calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions=0)` that computes an employee's net pay for a single pay period. First, subtract `pre_tax_deductions` (such as health insurance premiums) from `gross_pay` to get taxable wages; taxable wages are never negative. Then compute federal withholding as `taxable_wages * federal_rate` and state withholding as `taxable_wages * state_rate`, rounding each withholding amount to the nearest cent using ROUND_HALF_UP. Net pay equals gross pay minus pre_tax_deductions, federal withholding, and state withholding, rounded to the nearest cent with ROUND_HALF_UP. All monetary values must be handled with `decimal.Decimal` (convert inputs from strings or floats via `str()` if needed), and the function must return a dict with keys 'taxable_wages', 'federal_withholding', 'state_withholding', and 'net_pay', each a Decimal rounded to 2 places. Example: `calculate_net_pay('2500.00', '0.15', '0.05', '200.00')` should return `{'taxable_wages': Decimal('2300.00'), 'federal_withholding': Decimal('345.00'), 'state_withholding': Decimal('115.00'), 'net_pay': Decimal('1840.00')}`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef calculate_net_pay(gross_pay, federal_rate, state_rate, pre_tax_deductions=0):\n \"\"\"Compute net pay after pre-tax deductions and tax withholdings.\n\n Args:\n gross_pay: gross wages for the pay period (number or numeric string).\n federal_rate: federal withholding rate as a fraction, e.g. 0.15.\n state_rate: state withholding rate as a fraction, e.g. 0.05.\n pre_tax_deductions: pre-tax deductions such as insurance premiums.\n\n Returns:\n Dict of Decimals rounded to 2 places with keys:\n 'taxable_wages', 'federal_withholding', 'state_withholding', 'net_pay'.\n \"\"\"\n def to_decimal(value):\n if isinstance(value, Decimal):\n return value\n return Decimal(str(value))\n\n gross = to_decimal(gross_pay)\n fed_rate = to_decimal(federal_rate)\n state_rate_d = to_decimal(state_rate)\n pre_tax = to_decimal(pre_tax_deductions)\n\n cents = Decimal('0.01')\n\n taxable_wages = gross - pre_tax\n if taxable_wages < 0:\n taxable_wages = Decimal('0')\n\n federal_withholding = (taxable_wages * fed_rate).quantize(cents, rounding=ROUND_HALF_UP)\n state_withholding = (taxable_wages * state_rate_d).quantize(cents, rounding=ROUND_HALF_UP)\n taxable_wages = taxable_wages.quantize(cents, rounding=ROUND_HALF_UP)\n\n net_pay = gross - pre_tax - federal_withholding - state_withholding\n net_pay = net_pay.quantize(cents, rounding=ROUND_HALF_UP)\n\n return {\n 'taxable_wages': taxable_wages,\n 'federal_withholding': federal_withholding,\n 'state_withholding': state_withholding,\n 'net_pay': net_pay,\n }\n\n\nif __name__ == '__main__':\n result = calculate_net_pay('2500.00', '0.15', '0.05', '200.00')\n print(result)\n assert result == {\n 'taxable_wages': Decimal('2300.00'),\n 'federal_withholding': Decimal('345.00'),\n 'state_withholding': Decimal('115.00'),\n 'net_pay': Decimal('1840.00'),\n }\n result2 = calculate_net_pay('1000.00', '0.12', '0.04', '1200.00')\n assert result2 == {\n 'taxable_wages': Decimal('0.00'),\n 'federal_withholding': Decimal('0.00'),\n 'state_withholding': Decimal('0.00'),\n 'net_pay': Decimal('-200.00'),\n }\n print('All checks passed.')"}], "meta": {"idx": 2488, "topic": "payroll calculations, withholdings, and deductions", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 889, "latency_s": 8.6}} +{"prompt": [{"role": "user", "content": "Implement an append-only audit ledger for a small bookkeeping system. Each entry records an account name, a description, a direction ('debit' or 'credit'), and a Decimal money amount rounded to 2 places with ROUND_HALF_EVEN. To make tampering detectable, every entry stores a `prev_hash` (the hash of the previous entry, or 'GENESIS' for the first entry) and its own `hash`, computed as sha256 of the string f\"{prev_hash}|{index}|{account}|{direction}|{amount}\" where amount is formatted with exactly 2 decimal places. Provide a class Ledger with methods: `add_entry(account, description, direction, amount)` that appends an entry and returns its hash (raising ValueError for invalid direction or non-positive amounts); `balance(account)` returning the net Decimal balance (credits minus debits, default 0); `verify()` returning True if every entry's hash chain is intact and recomputation matches stored hashes, False otherwise; and `tamper(index, new_amount)` that mutates a stored amount (simulating fraud) without fixing hashes. Example: adding entries debit 'cash' 100.005 (stored as 100.00 or 100.01 per banker's rounding), credit 'cash' 25.50, then balance('cash') is Decimal('-74.50'); verify() is True before tamper(0, 999.99) and False after."}], "completion": [{"role": "assistant", "content": "import hashlib\nfrom decimal import Decimal, ROUND_HALF_EVEN\n\n\nclass Ledger:\n def __init__(self):\n self.entries = []\n\n @staticmethod\n def _fmt(amount):\n return str(amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN))\n\n def _compute_hash(self, prev_hash, index, account, direction, amount):\n data = f\"{prev_hash}|{index}|{account}|{direction}|{self._fmt(amount)}\"\n return hashlib.sha256(data.encode()).hexdigest()\n\n def add_entry(self, account, description, direction, amount):\n if direction not in ('debit', 'credit'):\n raise ValueError(\"direction must be 'debit' or 'credit'\")\n amount = Decimal(str(amount)).quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN)\n if amount <= 0:\n raise ValueError(\"amount must be positive\")\n prev_hash = self.entries[-1]['hash'] if self.entries else 'GENESIS'\n index = len(self.entries)\n h = self._compute_hash(prev_hash, index, account, direction, amount)\n entry = {\n 'index': index,\n 'account': account,\n 'description': description,\n 'direction': direction,\n 'amount': amount,\n 'prev_hash': prev_hash,\n 'hash': h,\n }\n self.entries.append(entry)\n return h\n\n def balance(self, account):\n total = Decimal('0.00')\n for e in self.entries:\n if e['account'] == account:\n sign = 1 if e['direction'] == 'credit' else -1\n total += sign * e['amount']\n return total.quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN)\n\n def verify(self):\n prev = 'GENESIS'\n for i, e in enumerate(self.entries):\n if e['index'] != i or e['prev_hash'] != prev:\n return False\n expected = self._compute_hash(e['prev_hash'], e['index'], e['account'],\n e['direction'], e['amount'])\n if e['hash'] != expected:\n return False\n prev = e['hash']\n return True\n\n def tamper(self, index, new_amount):\n self.entries[index]['amount'] = Decimal(str(new_amount)).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_EVEN)\n\n\nif __name__ == '__main__':\n led = Ledger()\n led.add_entry('cash', 'opening purchase', 'debit', '100.005')\n led.add_entry('cash', 'sale', 'credit', '25.50')\n print(led.balance('cash')) # -74.50\n print(led.verify()) # True\n led.tamper(0, '999.99')\n print(led.verify()) # False"}], "meta": {"idx": 2489, "topic": "audit trails and immutable entry logs", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 983, "latency_s": 8.6}} +{"prompt": [{"role": "user", "content": "You are reconciling a small agency's commission ledger. Write a function `split_commission(gross_sales, commission_rate, tip_rate, tip_recipients)` that takes a gross sales amount (Decimal string), a commission rate (Decimal string, e.g. '0.10' for 10%), a tip rate (Decimal string), and a list of recipient names. The function must: (1) compute the commission as gross_sales * commission_rate, (2) compute the tip pool as gross_sales * tip_rate, (3) split the tip pool evenly among recipients using banker's rounding (ROUND_HALF_EVEN) to the nearest cent, (4) assign any residual cents (the difference between the tip pool and the sum of the rounded shares) to the recipients in alphabetical order, one cent each, until the residual is exhausted. All intermediate money values must use Decimal with 2-decimal-place quantization. Return a dict mapping each recipient name to their total tip share (Decimal), plus the keys 'commission' and 'remaining_gross' (gross minus commission minus tip pool). Example: split_commission('100.00', '0.10', '0.03', ['ana', 'bob', 'cy']) -> commission = 10.00, tip pool = 3.00, each share = 1.00, so {'ana': Decimal('1.00'), 'bob': Decimal('1.00'), 'cy': Decimal('1.00'), 'commission': Decimal('10.00'), 'remaining_gross': Decimal('87.00')}. If the tip pool of 1.00 is split among 3 recipients, each gets 0.33 and the extra 0.01 goes to the alphabetically first recipient."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_EVEN\n\n\ndef split_commission(gross_sales, commission_rate, tip_rate, tip_recipients):\n CENT = Decimal('0.01')\n\n def money(value):\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_EVEN)\n\n gross = money(gross_sales)\n commission = money(gross * Decimal(commission_rate))\n tip_pool = money(gross * Decimal(tip_rate))\n\n result = {}\n if tip_recipients:\n n = len(tip_recipients)\n raw_share = tip_pool / Decimal(n)\n base_share = money(raw_share)\n for name in tip_recipients:\n result[name] = base_share\n\n residual = money(tip_pool - base_share * n)\n if residual > 0:\n extra_cent = CENT\n for name in sorted(tip_recipients):\n if residual <= 0:\n break\n result[name] = money(result[name] + extra_cent)\n residual = money(residual - extra_cent)\n else:\n if tip_pool != 0:\n raise ValueError('Tip pool is nonzero but there are no recipients')\n\n result['commission'] = commission\n result['remaining_gross'] = money(gross - commission - tip_pool)\n return result\n\n\nif __name__ == '__main__':\n print(split_commission('100.00', '0.10', '0.03', ['ana', 'bob', 'cy']))\n print(split_commission('100.00', '0.10', '0.01', ['ana', 'bob', 'cy']))"}], "meta": {"idx": 2490, "topic": "commission, tip, and percentage splits", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 713, "latency_s": 5.8}} +{"prompt": [{"role": "user", "content": "A bookkeeper must reconcile a simple-interest loan ledger. Given a principal amount (Decimal), an annual interest rate as a percentage (e.g. 5.5 for 5.5%), a loan term in whole months, and a monthly payment amount (Decimal), simulate the ledger month by month: each month, interest accrues on the outstanding balance at (annual rate / 12) rounded to the nearest cent (ROUND_HALF_UP), then the payment is applied. The loan is paid off when the balance reaches zero or below (final payment is capped at the balance plus that month's interest). Write a function `amortize(principal, annual_rate_pct, months, monthly_payment)` that returns a list of ledger entries, each a tuple `(month, interest, payment, balance)` with all money values as Decimal rounded to cents, plus the total interest paid as a Decimal. If the loan is not fully repaid after the given number of months, raise ValueError('loan not repaid'). Example: principal=Decimal('1000.00'), rate=12, months=3, payment=Decimal('350.00') yields entries [(1, Decimal('10.00'), Decimal('350.00'), Decimal('660.00')), (2, Decimal('6.60'), Decimal('350.00'), Decimal('316.60')), (3, Decimal('3.17'), Decimal('319.77'), Decimal('0.00'))] and total interest Decimal('19.77')."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal('0.01')\n\ndef _cents(value):\n return Decimal(value).quantize(CENT, rounding=ROUND_HALF_UP)\n\ndef amortize(principal, annual_rate_pct, months, monthly_payment):\n principal = Decimal(principal)\n monthly_payment = Decimal(monthly_payment)\n monthly_rate = Decimal(annual_rate_pct) / Decimal('100') / Decimal('12')\n balance = _cents(principal)\n entries = []\n total_interest = Decimal('0.00')\n for month in range(1, int(months) + 1):\n if balance <= 0:\n break\n interest = _cents(balance * monthly_rate)\n balance = _cents(balance + interest)\n payment = min(monthly_payment, balance)\n payment = _cents(payment)\n balance = _cents(balance - payment)\n total_interest = _cents(total_interest + interest)\n entries.append((month, interest, payment, balance))\n if balance > 0:\n raise ValueError('loan not repaid')\n return entries, total_interest\n\nif __name__ == '__main__':\n entries, total = amortize(Decimal('1000.00'), 12, 3, Decimal('350.00'))\n for e in entries:\n print(e)\n print('Total interest:', total)\n assert entries == [\n (1, Decimal('10.00'), Decimal('350.00'), Decimal('660.00')),\n (2, Decimal('6.60'), Decimal('350.00'), Decimal('316.60')),\n (3, Decimal('3.17'), Decimal('319.77'), Decimal('0.00')),\n ]\n assert total == Decimal('19.77')\n print('All checks passed.')"}], "meta": {"idx": 2485, "topic": "interest calculation and payment schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 692, "latency_s": 34.9}} +{"prompt": [{"role": "user", "content": "A bookkeeping utility must post a monthly office-rent expense that recurs on the same day of each month. Write a function `post_recurring_rent(start_year, start_month, day, amount, months)` that generates journal entries for `months` consecutive months starting at (start_year, start_month). Each entry is a tuple `(year, month, day, 'Rent Expense', 'Cash', amount)` where amount is a Decimal rounded to 2 places. If the given day does not exist in a month (e.g. day 31 in a 30-day month), roll back to the last valid day of that month. Use `calendar` and `decimal` from the standard library. For example, `post_recurring_rent(2024, 1, 31, Decimal('1200.00'), 3)` returns [(2024, 1, 31, ...), (2024, 2, 29, ...), (2024, 3, 31, ...)] because 2024 is a leap year."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom decimal import Decimal, ROUND_HALF_UP\n\ndef post_recurring_rent(start_year, start_month, day, amount, months):\n entries = []\n year, month = start_year, start_month\n amt = Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n for _ in range(months):\n last_day = calendar.monthrange(year, month)[1]\n actual_day = min(day, last_day)\n entries.append((year, month, actual_day, 'Rent Expense', 'Cash', amt))\n month += 1\n if month > 12:\n month = 1\n year += 1\n return entries\n\nif __name__ == '__main__':\n for e in post_recurring_rent(2024, 1, 31, Decimal('1200.00'), 3):\n print(e)"}], "meta": {"idx": 2493, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 375, "latency_s": 4.7}} +{"prompt": [{"role": "user", "content": "A petty cash fund starts with a fixed imprest amount (e.g., $100.00) and is replenished back to that amount at the end of a period. Write a function `replenishment_report(entries, imprest)` that takes a list of petty cash entries and the imprest amount. Each entry is a tuple `(description, amount)` where `amount` is a Decimal representing cash paid out of the fund. The function must compute, using Decimal arithmetic with cents (2-decimal) rounding, the total disbursed, the cash remaining in the fund (imprest minus total disbursed), and the replenishment amount needed to restore the fund to the imprest level. It returns a dictionary with keys 'total_disbursed', 'cash_on_hand', and 'replenish', each a Decimal rounded to 2 decimal places. Example: entries = [('postage', Decimal('4.55')), ('snacks', Decimal('12.40')), ('taxi', Decimal('8.05'))] with imprest = Decimal('100.00') should return {'total_disbursed': Decimal('25.00'), 'cash_on_hand': Decimal('75.00'), 'replenish': Decimal('25.00')}. If total disbursements ever exceed the imprest, raise a ValueError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\ndef _cents(d):\n return d.quantize(TWO, rounding=ROUND_HALF_UP)\n\ndef replenishment_report(entries, imprest):\n imprest = _cents(Decimal(str(imprest)))\n total = Decimal('0.00')\n for description, amount in entries:\n amount = _cents(Decimal(str(amount)))\n total += amount\n total = _cents(total)\n if total > imprest:\n raise ValueError(f\"Disbursements ({total}) exceed imprest ({imprest})\")\n cash_on_hand = _cents(imprest - total)\n replenish = _cents(imprest - cash_on_hand)\n return {\n 'total_disbursed': total,\n 'cash_on_hand': cash_on_hand,\n 'replenish': replenish,\n }\n\nif __name__ == '__main__':\n entries = [\n ('postage', Decimal('4.55')),\n ('snacks', Decimal('12.40')),\n ('taxi', Decimal('8.05')),\n ]\n print(replenishment_report(entries, Decimal('100.00')))"}], "meta": {"idx": 2494, "topic": "petty cash logs and replenishment", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 516, "latency_s": 4.8}} +{"prompt": [{"role": "user", "content": "You are given a list of ledger entries for a small business. Each entry is a tuple (account, direction, amount) where account is a string like 'Cash', 'Revenue', 'Rent Expense', 'Accounts Payable', direction is 'D' (debit) or 'C' (credit), and amount is a string representing a decimal amount (e.g. '120.50'). Write a function summarize(entries) that returns a tuple (net_income, total_assets, total_liabilities_and_equity). Net income equals total credits minus total debits for revenue accounts (accounts containing the word 'Revenue') minus total debits minus total credits for expense accounts (accounts containing the word 'Expense'). Total assets equals the sum of debit-minus-credit amounts for asset accounts (accounts containing 'Cash', 'Bank', or 'Receivable'), and total liabilities_and_equity equals the sum of credit-minus-debit amounts for all other accounts, plus net income. Use Decimal for all arithmetic and round each result to 2 decimal places with ROUND_HALF_UP. For example, summarize([('Cash','D','1000.00'),('Revenue','C','1000.00'),('Rent Expense','D','250.50'),('Cash','C','250.50')]) should return (Decimal('749.50'), Decimal('749.50'), Decimal('749.50')) since revenue is 1000.00, expenses are 250.50, net income is 749.50, assets are 1000.00 - 250.50 = 749.50, and liabilities/equity (starting at 0 plus net income) is 749.50."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nASSET_KEYWORDS = ('Cash', 'Bank', 'Receivable')\n\ndef _round2(x):\n return x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n\ndef summarize(entries):\n revenue = Decimal('0')\n expenses = Decimal('0')\n assets = Decimal('0')\n other = Decimal('0')\n for account, direction, amount in entries:\n amt = Decimal(amount)\n debit = amt if direction == 'D' else Decimal('0')\n credit = amt if direction == 'C' else Decimal('0')\n if 'Revenue' in account:\n revenue += credit - debit\n elif 'Expense' in account:\n expenses += debit - credit\n elif any(k in account for k in ASSET_KEYWORDS):\n assets += debit - credit\n else:\n other += credit - debit\n net_income = revenue - expenses\n total_assets = assets\n total_le = other + net_income\n return (_round2(net_income), _round2(total_assets), _round2(total_le))\n\nif __name__ == '__main__':\n result = summarize([('Cash','D','1000.00'),('Revenue','C','1000.00'),('Rent Expense','D','250.50'),('Cash','C','250.50')])\n print(result)\n assert result == (Decimal('749.50'), Decimal('749.50'), Decimal('749.50'))"}], "meta": {"idx": 2487, "topic": "summarizing ledgers into P&L and balance-sheet figures", "difficulty": "easy", "provider": "novita", "in_tokens": 204, "out_tokens": 700, "latency_s": 7.2}} +{"prompt": [{"role": "user", "content": "You are maintaining a small general ledger. Each transaction has a unique id, a date string 'YYYY-MM-DD', and a list of lines, where each line is a (account, amount) pair; debit amounts are positive and credits are negative, and every transaction must balance to zero. Implement a Ledger class with these operations: post(txn_id, date, lines) adds a transaction (raise ValueError if the id already exists, the lines are empty, or the amounts do not sum to exactly 0); void(txn_id) marks a transaction as voided, meaning its lines no longer contribute to any balance, but the original amounts are remembered; reverse(txn_id, new_id, date) posts a new transaction that is an exact mirror (every amount negated) of the original transaction's lines at the time it was originally posted (raise ValueError if txn_id is voided or missing, or new_id already exists); balance(account) returns the net sum as a Decimal of all non-voided line amounts for that account, and history() returns a list of (txn_id, date, 'posted'|'voided') tuples in chronological order of posting (ties broken by insertion order). All money arithmetic must use Decimal with cents-level precision: store amounts as Decimal rounded to 2 places using ROUND_HALF_UP at post time, and reject any line whose amount has more than 2 decimal places before rounding only if it would change value (e.g. 10.001 is rejected, 10.000 is fine). Example: posting txn 'T1' on '2024-01-05' with lines [('cash', Decimal('100.00')), ('revenue', Decimal('-100.00'))], then voiding 'T1' leaves balance('cash') == Decimal('0.00'); reversing a voided txn raises ValueError."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\nTWO = Decimal('0.01')\n\n\ndef _clean_amount(value):\n d = Decimal(str(value))\n rounded = d.quantize(TWO, rounding=ROUND_HALF_UP)\n if rounded != d:\n raise ValueError('amount has more than 2 decimal places: %s' % d)\n return rounded\n\n\nclass Ledger:\n def __init__(self):\n self._txns = {}\n self._order = []\n\n def post(self, txn_id, date, lines):\n if txn_id in self._txns:\n raise ValueError('duplicate transaction id: %s' % txn_id)\n if not lines:\n raise ValueError('transaction must have at least one line')\n cleaned = []\n total = Decimal('0.00')\n for account, amount in lines:\n amt = _clean_amount(amount)\n cleaned.append((account, amt))\n total += amt\n if total != 0:\n raise ValueError('transaction does not balance to zero')\n self._txns[txn_id] = {'id': txn_id, 'date': date, 'lines': cleaned, 'voided': False}\n self._order.append(txn_id)\n\n def void(self, txn_id):\n txn = self._txns.get(txn_id)\n if txn is None:\n raise ValueError('unknown transaction: %s' % txn_id)\n txn['voided'] = True\n\n def reverse(self, txn_id, new_id, date):\n txn = self._txns.get(txn_id)\n if txn is None:\n raise ValueError('unknown transaction: %s' % txn_id)\n if txn['voided']:\n raise ValueError('cannot reverse a voided transaction: %s' % txn_id)\n if new_id in self._txns:\n raise ValueError('duplicate transaction id: %s' % new_id)\n reversed_lines = [(acct, -amt) for acct, amt in txn['lines']]\n self.post(new_id, date, reversed_lines)\n\n def balance(self, account):\n total = Decimal('0.00')\n for txn_id in self._order:\n txn = self._txns[txn_id]\n if txn['voided']:\n continue\n for acct, amt in txn['lines']:\n if acct == account:\n total += amt\n return total\n\n def history(self):\n return [(tid, self._txns[tid]['date'], 'voided' if self._txns[tid]['voided'] else 'posted') for tid in self._order]"}], "meta": {"idx": 2491, "topic": "correcting entries, reversals, and voided transactions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 976, "latency_s": 14.3}} +{"prompt": [{"role": "user", "content": "A small business posts a recurring monthly rent expense to its ledger. The rent is 1250.00 and is posted on the same day-of-month every month, starting from a given start date, for a given number of months. Write a function `post_recurring_rent(start_date, months, amount)` that takes a start date string in ISO format (YYYY-MM-DD), an integer number of monthly postings, and a Decimal amount, and returns a list of (date_string, Decimal) tuples representing each posting. The posting date for each subsequent month is the same day-of-month; if that day does not exist in a month (e.g. day 31 in April), use the last day of that month. Amounts must be exact Decimal values with two decimal places. For example, `post_recurring_rent('2024-01-31', 3, Decimal('1250.00'))` returns [('2024-01-31', Decimal('1250.00')), ('2024-02-29', Decimal('1250.00')), ('2024-03-31', Decimal('1250.00'))] because 2024 is a leap year, so February has 29 days."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal\nfrom datetime import date\nimport calendar\n\ndef post_recurring_rent(start_date, months, amount):\n d = date.fromisoformat(start_date)\n postings = []\n amt = Decimal(amount).quantize(Decimal('0.01'))\n year, month, day = d.year, d.month, d.day\n for i in range(months):\n m = month + i\n y = year + (m - 1) // 12\n m = (m - 1) % 12 + 1\n last_day = calendar.monthrange(y, m)[1]\n post_day = min(day, last_day)\n postings.append((date(y, m, post_day).isoformat(), amt))\n return postings\n\nif __name__ == '__main__':\n result = post_recurring_rent('2024-01-31', 3, Decimal('1250.00'))\n print(result)\n assert result == [\n ('2024-01-31', Decimal('1250.00')),\n ('2024-02-29', Decimal('1250.00')),\n ('2024-03-31', Decimal('1250.00')),\n ]"}], "meta": {"idx": 2497, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 460, "latency_s": 5.6}} +{"prompt": [{"role": "user", "content": "Write a set of unit tests for a small accounting module using `unittest` (standard library only). The module contains a `Ledger` class that stores entries as `(description, Decimal amount)` pairs and a `balance()` method returning the sum of all amounts as a `Decimal`, plus a module-level function `round_to_cents(value)` that rounds a `Decimal` to 2 decimal places using banker's rounding (ROUND_HALF_EVEN). Your task: implement the `Ledger` class and `round_to_cents` function, and then write a `unittest.TestCase` class `TestLedger` that thoroughly tests them. The tests must cover: (1) an empty ledger has balance exactly Decimal('0.00'), (2) adding entries of Decimal('12.34') and Decimal('-7.16') yields Decimal('5.18'), (3) floats are rejected with a `TypeError` when added as entries, (4) `round_to_cents(Decimal('2.675'))` equals `Decimal('2.68')` when the input has enough precision, and (5) `round_to_cents(Decimal('2.5'))` equals `Decimal('2')` (banker's rounding of an exact half to even). Worked example: a ledger with entries Decimal('100.00'), Decimal('-30.25'), and Decimal('5.25') must report balance Decimal('75.00'). Run all tests with `unittest.main()` and ensure the entire script passes when executed."}], "completion": [{"role": "assistant", "content": "import unittest\nfrom decimal import Decimal, ROUND_HALF_EVEN\n\n\nclass Ledger:\n \"\"\"A simple accounting ledger storing Decimal entries.\"\"\"\n\n def __init__(self):\n self._entries = []\n\n def add_entry(self, description, amount):\n if not isinstance(amount, Decimal):\n raise TypeError(\"amount must be a decimal.Decimal, got %r\" % type(amount).__name__)\n if not isinstance(description, str):\n raise TypeError(\"description must be a string\")\n self._entries.append((description, amount))\n\n def balance(self):\n total = sum((amount for _, amount in self._entries), Decimal(\"0\"))\n return total.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_EVEN)\n\n def entries(self):\n return list(self._entries)\n\n\ndef round_to_cents(value):\n \"\"\"Round a Decimal to cents using banker's rounding (ROUND_HALF_EVEN).\"\"\"\n if not isinstance(value, Decimal):\n raise TypeError(\"value must be a decimal.Decimal\")\n return value.quantize(Decimal(\"0.01\"), rounding=ROUND_HALF_EVEN)\n\n\nclass TestLedger(unittest.TestCase):\n def test_empty_ledger_balance_is_zero(self):\n ledger = Ledger()\n self.assertEqual(ledger.balance(), Decimal(\"0.00\"))\n\n def test_balance_of_simple_entries(self):\n ledger = Ledger()\n ledger.add_entry(\"sale\", Decimal(\"12.34\"))\n ledger.add_entry(\"refund\", Decimal(\"-7.16\"))\n self.assertEqual(ledger.balance(), Decimal(\"5.18\"))\n\n def test_worked_example(self):\n ledger = Ledger()\n ledger.add_entry(\"opening\", Decimal(\"100.00\"))\n ledger.add_entry(\"purchase\", Decimal(\"-30.25\"))\n ledger.add_entry(\"fee\", Decimal(\"5.25\"))\n self.assertEqual(ledger.balance(), Decimal(\"75.00\"))\n\n def test_float_entries_rejected(self):\n ledger = Ledger()\n with self.assertRaises(TypeError):\n ledger.add_entry(\"bad\", 12.34)\n\n def test_round_to_cents_half_up_case_with_precision(self):\n # 2.675 with sufficient precision rounds to 2.68 under HALF_EVEN\n # because the digit before is 7 (odd) -> rounds up to even 8.\n self.assertEqual(round_to_cents(Decimal(\"2.675\")), Decimal(\"2.68\"))\n\n def test_round_to_cents_bankers_even(self):\n # Exact half 2.5 rounds to even -> 2\n self.assertEqual(round_to_cents(Decimal(\"2.5\")), Decimal(\"2\"))\n\n def test_round_to_cents_negative_even(self):\n self.assertEqual(round_to_cents(Decimal(\"-3.5\")), Decimal(\"-4\"))\n\n def test_round_to_cents_rejects_float(self):\n with self.assertRaises(TypeError):\n round_to_cents(2.675)\n\n\nif __name__ == \"__main__\":\n unittest.main()"}], "meta": {"idx": 2495, "topic": "unit tests for accounting functions", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 1008, "latency_s": 8.3}} +{"prompt": [{"role": "user", "content": "You are given a chart of accounts and a list of expense transactions that must be categorized into accounts. Each account has a code (string), a name, and a type (one of 'Expense', 'Asset', 'Liability'). Each transaction is a tuple (date, payee, amount_string, category_hint). Some transactions have a category_hint that matches an account name exactly; those are assigned directly. Others must be assigned by a fallback rule: if the payee contains the substring 'rent' (case-insensitive), assign to the account named 'Rent'; if it contains 'utility' or 'utilities', assign to 'Utilities'; otherwise assign to 'Miscellaneous Expense'. The account balance for each account is the sum of assigned transaction amounts (which may be negative for credits). Write a function `categorize(accounts, transactions)` that returns a dict mapping account code to the total assigned amount as a Decimal rounded to 2 decimal places (ROUND_HALF_UP), including accounts with no assigned transactions (balance 0.00). Also return the total of all Expense-type account balances. Example: accounts = [('5000','Rent','Expense'), ('5100','Utilities','Expense'), ('5900','Miscellaneous Expense','Expense'), ('1000','Cash','Asset')], transactions = [('2024-01-05','Landlord Rent Co','1200.00',''), ('2024-01-06','City Utilities','85.505',''), ('2024-01-07','Coffee Shop','12.25','Miscellaneous Expense'), ('2024-01-08','Refund from Utility','Utilities','-50.00','')]. The result should be balances {'5000': Decimal('1200.00'), '5100': Decimal('35.51'), '5900': Decimal('12.25'), '1000': Decimal('0.00')} and total expense Decimal('1247.76'). Use Decimal arithmetic throughout; raise ValueError if a transaction hint matches no account name."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\n\ndef categorize(accounts, transactions):\n name_to_code = {}\n balances = {}\n for code, name, acct_type in accounts:\n name_to_code[name] = code\n balances[code] = Decimal('0.00')\n\n def assign(payee, hint):\n if hint:\n if hint not in name_to_code:\n raise ValueError('Unknown account name in hint: ' + hint)\n return name_to_code[hint]\n p = payee.lower()\n if 'rent' in p:\n return name_to_code['Rent']\n if 'utility' in p or 'utilities' in p:\n return name_to_code['Utilities']\n return name_to_code['Miscellaneous Expense']\n\n for date, payee, amount_str, hint in transactions:\n code = assign(payee, hint)\n balances[code] += Decimal(amount_str)\n\n q = Decimal('0.01')\n rounded = {code: bal.quantize(q, rounding=ROUND_HALF_UP) for code, bal in balances.items()}\n\n expense_total = Decimal('0.00')\n for code, name, acct_type in accounts:\n if acct_type == 'Expense':\n expense_total += rounded[code]\n expense_total = expense_total.quantize(q, rounding=ROUND_HALF_UP)\n\n return rounded, expense_total\n\nif __name__ == '__main__':\n accounts = [\n ('5000', 'Rent', 'Expense'),\n ('5100', 'Utilities', 'Expense'),\n ('5900', 'Miscellaneous Expense', 'Expense'),\n ('1000', 'Cash', 'Asset'),\n ]\n transactions = [\n ('2024-01-05', 'Landlord Rent Co', '1200.00', ''),\n ('2024-01-06', 'City Utilities', '85.505', ''),\n ('2024-01-07', 'Coffee Shop', '12.25', 'Miscellaneous Expense'),\n ('2024-01-08', 'Refund from Utility', 'Utilities', '-50.00'),\n ]\n balances, total = categorize(accounts, transactions)\n print(balances)\n print(total)"}], "meta": {"idx": 2496, "topic": "chart of accounts and expense categorization", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 897, "latency_s": 9.3}} +{"prompt": [{"role": "user", "content": "Write a function `closing_entries(trial_balance, adjustments)` that performs period-end closing for a small manual ledger. The `trial_balance` is a dict mapping account names to their pre-closing balances in cents (positive = debit, negative = credit), and `adjustments` is a list of tuples `(account, amount_cents)` applied in order. Accounts are classified as follows: names starting with 'revenue', 'expense', or the exact name 'income_summary' are temporary accounts; everything else is permanent. Closing proceeds in two steps: (1) zero out each revenue account by posting the offsetting amount to 'income_summary', (2) zero out each expense account by posting the offsetting amount to 'income_summary', then transfer the resulting 'income_summary' balance to an account named 'retained_earnings'. The function must return a dict with keys 'closing_entries', a list of tuples (account, amount_cents) representing each posted entry, and 'post_closing_balances', a dict of all permanent accounts plus 'retained_earnings' with their final balances in cents. Temporary accounts must have zero balance after closing. Use integer cents throughout and ensure the books balance (sum of all debits equals sum of all credits) before returning; raise ValueError if they do not. Example: trial_balance = {'cash': 10000, 'revenue_sales': -5000, 'expense_rent': 2000}, adjustments = [('expense_rent', 500)] gives closing entries [('revenue_sales', 5000), ('income_summary', -5000), ('expense_rent', -2500), ('income_summary', 2500), ('income_summary', -2500), ('retained_earnings', 2500)] and post-closing balances {'cash': 10000, 'retained_earnings': 2500}. Note the expense rent balance is 2500 after the adjustment (2000 + 500 debit), so closing credits expense_rent by 2500."}], "completion": [{"role": "assistant", "content": "def closing_entries(trial_balance, adjustments):\n balances = dict(trial_balance)\n for account, amount in adjustments:\n balances[account] = balances.get(account, 0) + amount\n\n def is_temporary(name):\n return name.startswith('revenue') or name.startswith('expense') or name == 'income_summary'\n\n closing = []\n\n def post(account, amount):\n closing.append((account, amount))\n balances[account] = balances.get(account, 0) + amount\n\n # Step 1: close revenue accounts (credit balances, negative) to income_summary\n for account in sorted(balances):\n if account.startswith('revenue') and balances[account] != 0:\n post(account, -balances[account])\n post('income_summary', balances[account])\n\n # Step 2: close expense accounts (debit balances, positive) to income_summary\n for account in sorted(balances):\n if account.startswith('expense') and balances[account] != 0:\n post(account, -balances[account])\n post('income_summary', balances[account])\n\n # Step 3: close income_summary to retained_earnings\n summary = balances.get('income_summary', 0)\n if summary != 0:\n post('income_summary', -summary)\n post('retained_earnings', summary)\n\n # Validation: all temporary accounts zero and books balance\n for account, bal in balances.items():\n if is_temporary(account) and bal != 0:\n raise ValueError('temporary account %s not zero after closing' % account)\n if sum(balances.values()) != 0:\n raise ValueError('books do not balance')\n\n post_closing = {a: b for a, b in balances.items() if not is_temporary(a)}\n return {'closing_entries': closing, 'post_closing_balances': post_closing}\n\n\nif __name__ == '__main__':\n result = closing_entries(\n {'cash': 10000, 'revenue_sales': -5000, 'expense_rent': 2000},\n [('expense_rent', 500)],\n )\n print(result)"}], "meta": {"idx": 2492, "topic": "period-end closing entries and routines", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 944, "latency_s": 21.5}} +{"prompt": [{"role": "user", "content": "A bookkeeper is reconciling a petty-cash ledger where each line item is recorded to four decimal places, but the final report must be in cents (two decimal places). Write a function `round_ledger(entries)` that takes a list of strings, each representing a monetary amount like '12.3456', and returns the total rounded to exactly 2 decimal places using standard ROUND_HALF_UP rounding (the common commercial rounding rule, where 2.345 rounds to 2.35). Use the `decimal.Decimal` type for all arithmetic, set the rounding mode on a local decimal context, and never use floats. For example, given ['0.005', '2.345', '10.0049'], the exact sum is 12.3549, which rounds to '12.35'; the function should return the string '12.35'. Your function must return the result as a string with exactly two digits after the decimal point."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, localcontext\n\ndef round_ledger(entries):\n with localcontext() as ctx:\n ctx.rounding = ROUND_HALF_UP\n total = Decimal('0')\n for e in entries:\n total += Decimal(e)\n return str(total.quantize(Decimal('0.01')))\n\nif __name__ == '__main__':\n print(round_ledger(['0.005', '2.345', '10.0049'])) # 12.35\n print(round_ledger(['1.005'])) # 1.01\n print(round_ledger(['0.004', '0.004', '0.004'])) # 0.01"}], "meta": {"idx": 2499, "topic": "currency rounding rules with the Decimal type", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 344, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "Your firm issues invoice numbers of the exact form INV-YY-SSSSSS-CC, where YY is a two-digit fiscal year, SSSSSS is a six-digit sequence (000000 is not allowed), and CC is a two-digit check digit computed as 97 - (int(YY + SSSSSS) % 97), zero-padded to two digits (so a remainder of 0 yields check digit 97). Using only the standard library, implement: (1) validate_number(number) returning True/False for format and check digit; (2) parse_invoice(line) for ledger lines of the form 'INV-...;client;amount;YYYY-MM-DD', raising ValueError if the invoice number is invalid, the amount does not match an optional-minus, plain decimal with at most 3 fractional digits (e.g. '150.005' or '-12.5'), or the date is not a real calendar date, and otherwise returning a dict with the number, client, the amount rounded to cents with ROUND_HALF_UP, and the date; (3) next_invoice_number(existing_numbers, fiscal_year) returning the next valid invoice number for that fiscal year (highest valid existing sequence + 1, or 000001 if none, raising ValueError if sequences are exhausted or fiscal_year is not 0-99); (4) process_ledger(lines) which parses each line, treats lines that fail parsing or reuse an already-seen invoice number as invalid, and returns {'valid_count': int, 'invalid_lines': list, 'client_totals': {client: str with 2 decimals}, 'grand_total': str with 2 decimals} where totals are sums of the per-invoice rounded amounts. Worked example: for the ledger ['INV-24-000042-86;Acme Corp;150.005;2024-01-15', 'INV-24-000042-86;Acme Corp;49.995;2024-02-01', 'INV-24-000043-85;Beta LLC;200.00;2024-02-10', 'INV-24-000123-05;Gamma Inc;120.456;2024-03-01', 'INV-24-000099-00;Bad Co;10.00;2024-03-02'] the second line is a duplicate (invalid), the last line has a wrong check digit (invalid, since 24000099 % 97 = 68 gives check digit 29), Acme Corp totals '150.01' (150.005 rounds half-up), Beta LLC '200.00', Gamma Inc '120.46', grand_total '470.47', valid_count 3; additionally next_invoice_number(valid_numbers_from_that_ledger, 24) is 'INV-24-000124-04' and next_invoice_number([], 25) is 'INV-25-000001-03'."}], "completion": [{"role": "assistant", "content": "import re\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nNUMBER_RE = re.compile(r'^INV-(\\d{2})-(\\d{6})-(\\d{2})$')\nAMOUNT_RE = re.compile(r'^-?\\d+(\\.\\d{1,3})?$')\nCENT = Decimal('0.01')\n\n\ndef check_digit(fiscal_year, seq):\n value = int('{:02d}{:06d}'.format(fiscal_year, seq))\n return 97 - (value % 97)\n\n\ndef validate_number(number):\n m = NUMBER_RE.match(number)\n if not m:\n return False\n yy = int(m.group(1))\n seq = int(m.group(2))\n cc = int(m.group(3))\n if seq == 0:\n return False\n return cc == check_digit(yy, seq)\n\n\ndef parse_invoice(line):\n parts = line.split(';')\n if len(parts) != 4:\n raise ValueError('malformed ledger line: {!r}'.format(line))\n number, client, amount_str, date_str = (p.strip() for p in parts)\n if not validate_number(number):\n raise ValueError('invalid invoice number: {!r}'.format(number))\n if not AMOUNT_RE.match(amount_str):\n raise ValueError('invalid amount: {!r}'.format(amount_str))\n amount = Decimal(amount_str)\n try:\n inv_date = date.fromisoformat(date_str)\n except ValueError:\n raise ValueError('invalid date: {!r}'.format(date_str))\n rounded = amount.quantize(CENT, rounding=ROUND_HALF_UP)\n return {\n 'number': number,\n 'client': client,\n 'amount': rounded,\n 'date': inv_date,\n }\n\n\ndef next_invoice_number(existing_numbers, fiscal_year):\n if not isinstance(fiscal_year, int) or not (0 <= fiscal_year <= 99):\n raise ValueError('fiscal_year must be an integer in 0..99')\n max_seq = 0\n for n in existing_numbers:\n m = NUMBER_RE.match(n)\n if not m:\n continue\n yy = int(m.group(1))\n seq = int(m.group(2))\n cc = int(m.group(3))\n if yy == fiscal_year and seq > 0 and cc == check_digit(yy, seq):\n if seq > max_seq:\n max_seq = seq\n seq = max_seq + 1\n if seq > 999999:\n raise ValueError('invoice sequence exhausted for fiscal year {:02d}'.format(fiscal_year))\n return 'INV-{:02d}-{:06d}-{:02d}'.format(fiscal_year, seq, check_digit(fiscal_year, seq))\n\n\ndef process_ledger(lines):\n seen = set()\n invalid_lines = []\n client_totals = {}\n grand_total = Decimal('0.00')\n valid_count = 0\n for line in lines:\n try:\n inv = parse_invoice(line)\n except ValueError:\n invalid_lines.append(line)\n continue\n if inv['number'] in seen:\n invalid_lines.append(line)\n continue\n seen.add(inv['number'])\n valid_count += 1\n client_totals[inv['client']] = client_totals.get(inv['client'], Decimal('0.00')) + inv['amount']\n grand_total += inv['amount']\n return {\n 'valid_count': valid_count,\n 'invalid_lines': invalid_lines,\n 'client_totals': {c: str(t.quantize(CENT)) for c, t in client_totals.items()},\n 'grand_total': str(grand_total.quantize(CENT)),\n }\n\n\nif __name__ == '__main__':\n ledger = [\n 'INV-24-000042-86;Acme Corp;150.005;2024-01-15',\n 'INV-24-000042-86;Acme Corp;49.995;2024-02-01',\n 'INV-24-000043-85;Beta LLC;200.00;2024-02-10',\n 'INV-24-000123-05;Gamma Inc;120.456;2024-03-01',\n 'INV-24-000099-00;Bad Co;10.00;2024-03-02',\n ]\n report = process_ledger(ledger)\n assert report['valid_count'] == 3\n assert report['invalid_lines'] == [ledger[1], ledger[4]]\n assert report['client_totals'] == {'Acme Corp': '150.01', 'Beta LLC': '200.00', 'Gamma Inc': '120.46'}\n assert report['grand_total'] == '470.47'\n\n valid_numbers = ['INV-24-000042-86', 'INV-24-000043-85', 'INV-24-000123-05']\n assert next_invoice_number(valid_numbers, 24) == 'INV-24-000124-04'\n assert next_invoice_number([], 25) == 'INV-25-000001-03'\n assert validate_number('INV-24-000042-86') is True\n assert validate_number('INV-24-000099-00') is False\n assert validate_number('INV-24-000000-31') is False\n print(report)\n print(next_invoice_number(valid_numbers, 24))\n print(next_invoice_number([], 25))"}], "meta": {"idx": 2444, "topic": "invoice generation, numbering, and parsing", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1590, "latency_s": 351.4}} +{"prompt": [{"role": "user", "content": "Write a program that generates a monthly amortization schedule for a fixed-rate loan and produces a bookkeeping-style ledger report. The loan is defined by a principal amount, an annual nominal interest rate (e.g. 5.5 for 5.5%), and a term in whole months. All monetary values must be computed with Python's Decimal, rounding each interest charge, payment split, and ending balance to exactly 2 decimal places using ROUND_HALF_UP. Each month, interest = previous balance * (annual rate / 100 / 12) rounded to cents; the fixed monthly payment is the standard amortization formula payment = P * r * (1+r)^n / ((1+r)^n - 1) where r is the monthly rate, rounded to cents; principal paid = payment - interest; the final payment must be adjusted so the ending balance is exactly 0.00. The report must print, for each month, a ledger line with the month number, payment, interest, principal, and ending balance, followed by a totals line showing total payments and total interest. Input: principal = Decimal('200000.00'), annual rate = Decimal('6.0'), term = 360 months. Your program should print the schedule; for example, month 1 should show payment 1199.10, interest 1000.00, principal 199.10, and ending balance 199800.90. Solve the task with a complete runnable program using only the standard library."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP, getcontext\n\ngetcontext().prec = 50\n\nCENT = Decimal('0.01')\n\n\ndef money(x):\n return Decimal(x).quantize(CENT, rounding=ROUND_HALF_UP)\n\n\ndef amortize(principal, annual_rate_pct, months):\n principal = money(principal)\n r = Decimal(annual_rate_pct) / Decimal(100) / Decimal(12)\n n = Decimal(months)\n if r == 0:\n payment = money(principal / n)\n else:\n growth = (Decimal(1) + r) ** n\n payment = money(principal * r * growth / (growth - Decimal(1)))\n\n schedule = []\n balance = principal\n total_paid = Decimal('0.00')\n total_interest = Decimal('0.00')\n\n for month in range(1, int(months) + 1):\n interest = money(balance * r)\n # Final payment adjusts so balance hits exactly zero.\n if month == months:\n pay = money(balance + interest)\n else:\n pay = payment\n principal_part = money(pay - interest)\n if principal_part > balance:\n principal_part = balance\n pay = money(balance + interest)\n balance = money(balance - principal_part)\n total_paid = money(total_paid + pay)\n total_interest = money(total_interest + interest)\n schedule.append((month, pay, interest, principal_part, balance))\n\n return schedule, total_paid, total_interest\n\n\ndef print_report(schedule, total_paid, total_interest):\n header = f\"{'Month':>5} {'Payment':>12} {'Interest':>12} {'Principal':>12} {'Balance':>14}\"\n print(header)\n print('-' * len(header))\n for month, pay, interest, principal_part, balance in schedule:\n print(f\"{month:>5} {pay:>12} {interest:>12} {principal_part:>12} {balance:>14}\")\n print('-' * len(header))\n print(f\"{'TOTAL':>5} {total_paid:>12} {total_interest:>12}\")\n\n\nif __name__ == '__main__':\n schedule, total_paid, total_interest = amortize(\n Decimal('200000.00'), Decimal('6.0'), 360\n )\n print_report(schedule, total_paid, total_interest)"}], "meta": {"idx": 2501, "topic": "loan and mortgage amortization schedules", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 844, "latency_s": 6.8}} +{"prompt": [{"role": "user", "content": "Write a function `aging_report(invoices, as_of)` that produces an accounts receivable aging report from a list of unpaid customer invoices. Each invoice is a tuple `(invoice_id, customer, due_date, amount)` where `due_date` is a `datetime.date` and `amount` is a `Decimal` representing the outstanding balance. The `as_of` parameter is a `datetime.date` for the report cutoff. Bucket each invoice's amount into one of four aging buckets based on days overdue: 'current' (0 or fewer days overdue), '1-30' (1-30 days), '31-60' (31-60 days), and '61+' (more than 60 days). Return a dict mapping each bucket name to a `Decimal` total, including all four buckets even if empty, and additionally include a key 'grand_total' with the sum of all buckets. Use `Decimal` arithmetic throughout and round each bucket total and the grand total to 2 decimal places with `ROUND_HALF_UP`. For example, with `as_of = date(2024, 6, 30)` and invoices `[('I1','Acme',date(2024,6,15),Decimal('100.00')), ('I2','Beta',date(2024,5,20),Decimal('250.50')), ('I3','Gamma',date(2024,3,1'),Decimal('75.25'))]`, the result should be `{'current': Decimal('100.00'), '1-30': Decimal('250.50'), '31-60': Decimal('0.00'), '61+': Decimal('75.25'), 'grand_total': Decimal('425.75')}`."}], "completion": [{"role": "assistant", "content": "from decimal import Decimal, ROUND_HALF_UP\nfrom datetime import date\n\n\ndef aging_report(invoices, as_of):\n buckets = {'current': Decimal('0'), '1-30': Decimal('0'),\n '31-60': Decimal('0'), '61+': Decimal('0')}\n for invoice_id, customer, due_date, amount in invoices:\n overdue_days = (as_of - due_date).days\n if overdue_days <= 0:\n bucket = 'current'\n elif overdue_days <= 30:\n bucket = '1-30'\n elif overdue_days <= 60:\n bucket = '31-60'\n else:\n bucket = '61+'\n buckets[bucket] += Decimal(amount)\n result = {k: v.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)\n for k, v in buckets.items()}\n result['grand_total'] = sum(buckets.values()).quantize(\n Decimal('0.01'), rounding=ROUND_HALF_UP)\n return result\n\n\nif __name__ == '__main__':\n invoices = [\n ('I1', 'Acme', date(2024, 6, 15), Decimal('100.00')),\n ('I2', 'Beta', date(2024, 5, 20), Decimal('250.50')),\n ('I3', 'Gamma', date(2024, 3, 1), Decimal('75.25')),\n ]\n print(aging_report(invoices, date(2024, 6, 30)))"}], "meta": {"idx": 2500, "topic": "accounts receivable and payable aging reports", "difficulty": "medium", "provider": "together", "in_tokens": 0, "out_tokens": 610, "latency_s": 8.0}} +{"prompt": [{"role": "user", "content": "A small business posts a monthly rent expense of 850.00 on the last day of every month, starting 2024-01-31, plus a weekly cleaning service of 60.00 every Friday starting 2024-01-05. Given a start date and an end date (inclusive), compute the total posted amount in that window using Decimal for exact money handling, and also return the number of rent postings and the number of cleaning postings. For example, from 2024-01-01 to 2024-03-31 inclusive, rent posts on Jan 31, Feb 29 (2024 is a leap year), and Mar 31 for 3 * 850.00 = 2550.00, and cleaning posts on every Friday: Jan 5, 12, 19, 26, Feb 2, 9, 16, 23, Mar 1, 8, 15, 22, 29 for 13 * 60.00 = 780.00, so the total is 3330.00 with 3 rent postings and 13 cleaning postings. Implement a function `total_postings(start: str, end: str) -> tuple[Decimal, int, int]` where dates are 'YYYY-MM-DD' strings; the answer tuple is (total amount, rent count, cleaning count)."}], "completion": [{"role": "assistant", "content": "from datetime import date, timedelta\nfrom decimal import Decimal\n\n\ndef total_postings(start: str, end: str) -> tuple:\n start_d = date.fromisoformat(start)\n end_d = date.fromisoformat(end)\n if end_d < start_d:\n return (Decimal(\"0.00\"), 0, 0)\n\n rent_amount = Decimal(\"850.00\")\n cleaning_amount = Decimal(\"60.00\")\n\n rent_count = 0\n d = start_d\n while d <= end_d:\n # last day of month check: tomorrow is a new month\n if (d + timedelta(days=1)).month != d.month:\n rent_count += 1\n d += timedelta(days=1)\n\n # Fridays from start_d to end_d\n cleaning_count = 0\n d = start_d\n offset = (4 - d.weekday()) % 7 # next Friday (weekday 4)\n d = d + timedelta(days=offset)\n while d <= end_d:\n cleaning_count += 1\n d += timedelta(days=7)\n\n total = rent_count * rent_amount + cleaning_count * cleaning_amount\n return (total, rent_count, cleaning_count)\n\n\nif __name__ == \"__main__\":\n result = total_postings(\"2024-01-01\", \"2024-03-31\")\n print(result) # (Decimal('3330.00'), 3, 13)\n assert result == (Decimal(\"3330.00\"), 3, 13)"}], "meta": {"idx": 2502, "topic": "recurring and calendar-based postings", "difficulty": "easy", "provider": "together", "in_tokens": 0, "out_tokens": 531, "latency_s": 6.1}} +{"prompt": [{"role": "user", "content": "You are given a journal of raw transactions for a small business, where each entry is a tuple (kind, \"YYYY-MM-DD\", amount_string, extra): kind is one of \"invoice\" (revenue earned on that date under accrual accounting), \"receipt\" (cash collected on that date), \"bill\" (expense incurred on that date), \"payment\" (cash paid out on that date), \"prepay\" (cash paid on that date for an expense that accrual accounting must spread over `extra` months starting on the payment date), or \"advance\" (cash received on that date for services that accrual accounting must spread over `extra` months starting on the receipt date). For \"prepay\"/\"advance\", the total is split so the first `extra`-1 monthly recognitions each equal (amount/extra) rounded to cents with ROUND_HALF_UP, and the final recognition takes the exact remainder; recognition dates fall on the same day-of-month for each of the `extra` consecutive months, clamped to the last valid day when a month is shorter. Write a function summarize(entries, year) that returns a dict with keys \"accrual_net_income\" (accrual revenue minus accrual expenses whose recognition dates fall in the given year), \"cash_net_income\" (cash receipts minus cash payments dated in the given year), and \"difference\" (accrual minus cash), all as Decimal values quantized to two decimal places, and raise ValueError for unknown kinds, non-positive amounts, or invalid month counts. Example: for year 2024 the entries [(\"invoice\",\"2024-03-15\",\"1200.00\",None), (\"receipt\",\"2024-04-10\",\"1200.00\",None), (\"bill\",\"2024-06-30\",\"500.00\",None), (\"payment\",\"2024-07-05\",\"500.00\",None), (\"prepay\",\"2024-11-01\",\"3600.00\",12), (\"advance\",\"2024-12-05\",\"900.00\",6)] give accrual_net_income 250.00 (1200.00 invoice revenue + 150.00 of the advance earned in 2024 \u2212 500.00 bill \u2212 600.00 of the prepay amortization recognized in 2024) and cash_net_income -2000.00, so difference is 2250.00."}], "completion": [{"role": "assistant", "content": "import calendar\nfrom datetime import date\nfrom decimal import Decimal, ROUND_HALF_UP\n\nCENT = Decimal(\"0.01\")\nZERO = Decimal(\"0.00\")\n\n\ndef _add_months(d, k):\n \"\"\"Return the date k months after d, keeping the day-of-month\n and clamping to the last valid day of the target month.\"\"\"\n y = d.year + (d.month - 1 + k) // 12\n m = (d.month - 1 + k) % 12 + 1\n last_day = calendar.monthrange(y, m)[1]\n return date(y, m, min(d.day, last_day))\n\n\ndef _monthly_shares(amount, months):\n \"\"\"Split amount into `months` shares: the first months-1 equal\n (amount/months) rounded half-up to cents; the last takes the remainder.\"\"\"\n per = (amount / months).quantize(CENT, ROUND_HALF_UP)\n shares = [per] * (months - 1)\n shares.append(amount - per * (months - 1))\n return shares\n\n\ndef summarize(entries, year):\n accrual_rev = ZERO\n accrual_exp = ZERO\n cash_rev = ZERO\n cash_exp = ZERO\n\n for e in entries:\n kind, dstr, amt_str, extra = e\n d = date.fromisoformat(dstr)\n amount = Decimal(amt_str).quantize(CENT, ROUND_HALF_UP)\n if amount <= ZERO:\n raise ValueError(\"amount must be positive: %r\" % (e,))\n\n if kind == \"invoice\":\n if d.year == year:\n accrual_rev += amount\n elif kind == \"receipt\":\n if d.year == year:\n cash_rev += amount\n elif kind == \"bill\":\n if d.year == year:\n accrual_exp += amount\n elif kind == \"payment\":\n if d.year == year:\n cash_exp += amount\n elif kind in (\"prepay\", \"advance\"):\n months = extra\n if not isinstance(months, int) or isinstance(months, bool) or months < 1:\n raise ValueError(\"months must be a positive integer: %r\" % (e,))\n shares = _monthly_shares(amount, months)\n if kind == \"prepay\":\n if d.year == year:\n cash_exp += amount\n for i in range(months):\n if _add_months(d, i).year == year:\n accrual_exp += shares[i]\n else: # \"advance\"\n if d.year == year:\n cash_rev += amount\n for i in range(months):\n if _add_months(d, i).year == year:\n accrual_rev += shares[i]\n else:\n raise ValueError(\"unknown entry kind: %r\" % (kind,))\n\n accrual_ni = (accrual_rev - accrual_exp).quantize(CENT, ROUND_HALF_UP)\n cash_ni = (cash_rev - cash_exp).quantize(CENT, ROUND_HALF_UP)\n return {\n \"accrual_net_income\": accrual_ni,\n \"cash_net_income\": cash_ni,\n \"difference\": (accrual_ni - cash_ni).quantize(CENT, ROUND_HALF_UP),\n }\n\n\nif __name__ == \"__main__\":\n entries = [\n (\"invoice\", \"2024-03-15\", \"1200.00\", None),\n (\"receipt\", \"2024-04-10\", \"1200.00\", None),\n (\"bill\", \"2024-06-30\", \"500.00\", None),\n (\"payment\", \"2024-07-05\", \"500.00\", None),\n (\"prepay\", \"2024-11-01\", \"3600.00\", 12),\n (\"advance\", \"2024-12-05\", \"900.00\", 6),\n ]\n result = summarize(entries, 2024)\n assert result[\"accrual_net_income\"] == Decimal(\"250.00\")\n assert result[\"cash_net_income\"] == Decimal(\"-2000.00\")\n assert result[\"difference\"] == Decimal(\"2250.00\")\n print(result)\n\n # End-of-month clamping: a 31st-day prepay spreads into shorter months.\n entries2 = [(\"advance\", \"2024-01-31\", \"100.00\", 3)]\n result2 = summarize(entries2, 2024)\n # Shares: 33.33, 33.33, 33.34; all three recognition dates (Jan 31,\n # Feb 29, Mar 31) fall in 2024, so full 100.00 is accrual revenue.\n assert result2[\"accrual_net_income\"] == Decimal(\"100.00\")\n assert result2[\"cash_net_income\"] == Decimal(\"100.00\")\n print(result2)"}], "meta": {"idx": 2478, "topic": "accrual versus cash basis adjustments", "difficulty": "hard", "provider": "together", "in_tokens": 0, "out_tokens": 1497, "latency_s": 93.6}}