id
stringlengths
20
20
family
stringclasses
1 value
skill
stringclasses
157 values
area
stringclasses
4 values
form
stringclasses
12 values
n_steps
int64
1
6
style
stringclasses
2 values
seed
dict
teacher
stringclasses
4 values
spec
stringlengths
377
1.48k
plan
listlengths
2
10
solution
stringlengths
176
3.65k
tests_teacher
stringlengths
398
2.6k
tests_independent
stringlengths
449
3.99k
independent_test_teacher
stringclasses
2 values
legacy
stringlengths
222
3.47k
⌀
bugfix
dict
verdict
dict
ol5-59c7d9e1d78eded6
code
sliding_window
alg
formatter
3
short
{ "kind": "og", "text": "houseboat (A boat or vessel designed or adapted for use as a residence, typically moored or navigable, providing living accommodation on water)", "sources": [ { "source": "opengloss", "id": "og-glossary:houseboat", "headword": "houseboat" } ] }
ds-v4.1-flash
We run three houseboats on the river and want a nightly berth report from the guest counts we log. Please write `longest_stretch(guests: list[int], budget: int) -> tuple[int, int]` and `format_berth_report(boats: list[HouseboatLog], *, width: int = 5) -> str`, where `HouseboatLog` is a frozen slotted dataclass holding ...
[ "Reject a negative budget and negative counts up front.", "Slide a window end forward, adding each count to a running total.", "While the total exceeds the budget, drop the leftmost night and advance the left pointer.", "Keep the widest window seen, preferring the earlier one on a tie.", "Format the report ...
"""Quiet stretches and a berth report for a small fleet of houseboats.""" from dataclasses import dataclass @dataclass(frozen=True, slots=True) class HouseboatLog: """Nightly guest counts and the guest budget allowed on one houseboat.""" name: str guests: tuple[int, ...] budget: int def longest_st...
from solution import HouseboatLog, format_berth_report, longest_stretch def test_longest_stretch_finds_the_widest_window() -> None: assert longest_stretch([1, 2, 3, 1, 1], 4) == (0, 2) def test_longest_stretch_prefers_the_earlier_tie() -> None: assert longest_stretch([1, 1, 5, 1, 1], 2) == (0, 2) def test...
from solution import HouseboatLog, format_berth_report, longest_stretch def test_longest_stretch_basic() -> None: assert longest_stretch([3, 1, 4, 1, 5], 5) == (0, 2) def test_longest_stretch_tie_returns_earlier() -> None: assert longest_stretch([2, 2, 2, 2], 4) == (0, 2) def test_longest_stretch_no_singl...
glm-5.3-flash
"""Quiet stretches and a berth report for a small fleet of houseboats.""" from typing import List, Tuple class HouseboatLog(object): """Nightly guest counts and the guest budget allowed on one houseboat.""" __slots__ = ("name", "guests", "budget") def __init__(self, name, guests, budget): # typ...
{ "mutant": "\"\"\"Quiet stretches and a berth report for a small fleet of houseboats.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass HouseboatLog:\n \"\"\"Nightly guest counts and the guest budget allowed on one houseboat.\"\"\"\n name: str\n guests: tuple[int, ...]\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-2f8fd89ac498c004
code
majority_vote
alg
class
2
short
{ "kind": "legal", "text": "What amount does the Secretary forgive? (the subject of 34 CFR 222.18, Education)", "sources": [ { "source": "ecfr", "id": "34 CFR 222.18", "agency": "OFFICE OF ELEMENTARY AND SECONDARY EDUCATION, DEPARTMENT OF EDUCATION" } ] }
ds-v4.1-flash
Under 34 CFR 222.18 the Secretary may forgive part of an overpayment, and a review panel keeps proposing amounts until one of them clearly wins. Please write a class `ForgivenessPoll` with a no-argument constructor and the methods `cast(amount: float) -> None`, `count_for(amount: float) -> int`, and `majority() -> floa...
[ "Keep the proposed amounts in a list on the instance.", "`majority` runs one pass of the majority-vote counter to find a candidate amount.", "It verifies the candidate with `count_for` against twice the number of proposals.", "`count_for` walks the stored amounts and counts equal values without touching state...
"""Tally proposed forgiveness amounts for one overpayment case.""" class ForgivenessPoll: """Collect proposed forgiveness amounts and report a strict majority.""" __slots__ = ("_amounts",) def __init__(self) -> None: self._amounts: list[float] = [] def cast(self, amount: float) -> None: ...
from solution import ForgivenessPoll def test_cast_is_recorded_by_count_for() -> None: poll = ForgivenessPoll() poll.cast(1200.0) poll.cast(950.0) poll.cast(1200.0) assert poll.count_for(1200.0) == 2 assert poll.count_for(950.0) == 1 assert poll.count_for(700.0) == 0 def test_count_for_d...
from solution import ForgivenessPoll def test_majority_requires_strict_majority() -> None: poll = ForgivenessPoll() poll.cast(100.0) poll.cast(200.0) assert poll.majority() is None poll.cast(100.0) assert poll.majority() == 100.0 def test_majority_empty_poll() -> None: poll = Forgiveness...
glm-5.3-flash
"""Tally proposed forgiveness amounts for one overpayment case.""" from typing import List, Optional class ForgivenessPoll(object): """Collect proposed forgiveness amounts and report a strict majority.""" def __init__(self) -> None: self._amounts = [] # type: List[float] def cast(self, amount:...
{ "mutant": "\"\"\"Tally proposed forgiveness amounts for one overpayment case.\"\"\"\n\nclass ForgivenessPoll:\n \"\"\"Collect proposed forgiveness amounts and report a strict majority.\"\"\"\n __slots__ = ('_amounts',)\n\n def __init__(self) -> None:\n self._amounts: list[float] = []\n\n def cast...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-4b3099b26bfe1949
code
typing_generics
py
dataclass_plus_fn
4
short
{ "kind": "public", "text": "choir rehearsals", "sources": [] }
ds-v4.1-flash
Two conductors are swapping rehearsal segments and want the plan to stay generic over whatever value each voice part carries. Write a module with the type alias `type Sheet[T] = dict[str, T]`, a dataclass `Segment[T]` with `slots=True` and fields `label: str` and `by_part: Sheet[T]`, plus `add_part[T](segment: Segment[...
[ "Declare the generic alias `Sheet[T]` and the slots dataclass `Segment[T]`.", "In `add_part`, reject an empty part name, copy the mapping and set the new value.", "In `collect`, walk segments in order and append each part's value into a gathered mapping.", "Return the gathered mapping, keeping first-seen inse...
from dataclasses import dataclass type Sheet[T] = dict[str, T] @dataclass(slots=True) class Segment[T]: """One rehearsal segment holding a value for each voice part.""" label: str by_part: Sheet[T] def add_part[T](segment: Segment[T], part: str, value: T) -> Segment[T]: """Return a copy of segment...
from solution import Segment, add_part, collect def test_add_part_leaves_original_alone() -> None: original = Segment(label="warmup", by_part={"alto": 4}) updated = add_part(original, "soprano", 3) assert original.by_part == {"alto": 4} assert updated.by_part == {"alto": 4, "soprano": 3} assert up...
from solution import Segment, add_part, collect def test_add_part_returns_fresh_segment() -> None: seg = Segment("warm-up", {"soprano": 1}) result = add_part(seg, "alto", 2) assert isinstance(result, Segment) assert result is not seg assert seg.by_part == {"soprano": 1} assert seg.label == "wa...
glm-5.3-flash
from typing import Dict, Generic, List, TypeVar T = TypeVar("T") class Segment(Generic[T]): """One rehearsal segment holding a value for each voice part.""" def __init__(self, label: str, by_part: Dict[str, T]) -> None: self.label = label self.by_part = by_part def add_part(segment: Segmen...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-1f47cf6ad2470c08
code
stable_sort
alg
dataclass_plus_fn
2
short
{ "kind": "og", "text": "mainsail (The principal sail on a sailing vessel, typically the largest sail attached to the mainmast and used to propel the vessel)", "sources": [ { "source": "opengloss", "id": "og-glossary:mainsail", "headword": "mainsail" } ] }
ds-v4.1-flash
A mainsail trim log needs a fixed reading order before it goes to the crew. Write a frozen dataclass `Trim` with slots and fields `sail: str`, `wind_knots: int` and `reef_points: int`, and a function `order_trims(trims: list[Trim]) -> list[Trim]` that returns the trims in reporting order. The order is by wind strength,...
[ "Define the frozen slots dataclass `Trim`.", "Sort a copy of the input by `sail`, the secondary key.", "Sort that result again by `wind_knots`, the primary key, relying on the stability of `sorted` to keep the sail order inside equal winds." ]
"""Reporting order for mainsail trim records.""" from dataclasses import dataclass @dataclass(slots=True, frozen=True) class Trim: """A mainsail trim: sail name, wind strength in knots and reef points.""" sail: str wind_knots: int reef_points: int def order_trims(trims: list[Trim]) -> list[Trim]: ...
from solution import Trim, order_trims def test_orders_by_wind_then_sail() -> None: trims = [ Trim(sail="jib", wind_knots=12, reef_points=1), Trim(sail="main", wind_knots=8, reef_points=2), Trim(sail="genoa", wind_knots=8, reef_points=0), ] assert [(t.wind_knots, t.sail) for t in o...
from solution import Trim, order_trims def _trim(sail: str, wind: int) -> Trim: return Trim(sail=sail, wind_knots=wind, reef_points=0) def test_order_trims_by_wind() -> None: trims: list[Trim] = [_trim("main", 12), _trim("main", 5)] assert order_trims(trims) == [_trim("main", 5), _trim("main", 12)] de...
glm-5.3-flash
"""Reporting order for mainsail trim records.""" from typing import List class Trim: """A mainsail trim record.""" def __init__(self, sail: str, wind_knots: int, reef_points: int) -> None: self.sail = sail self.wind_knots = wind_knots self.reef_points = reef_points def order_trims(...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-feb23b3c44214335
code
rate_table_lookup
alg
module
1
short
{ "kind": "public", "text": "warranty claim windows", "sources": [] }
ds-v4.1-flash
We need a small helper module for warranty claim processing windows. Please write `lookup_fee_rate(bands: list[FeeBand], days: int) -> float`, `claim_fee(bands: list[FeeBand], days: int, amount: float) -> float`, and `describe_claim(bands: list[FeeBand], days: int, amount: float) -> str`, all in one module, with a publ...
[ "Store bands as `tuple[int, float]` and bisect on the threshold, using an infinite rate to keep the tuple comparison well formed.", "Subtract one from `bisect_right` to get the band index, raising `ValueError` when it is negative.", "Multiply the amount by the rate in `claim_fee`, rounding to two decimals.", ...
import bisect type FeeBand = tuple[int, float] def lookup_fee_rate(bands: list[FeeBand], days: int) -> float: """Return the rate of the band with the largest threshold at or below days.""" index = bisect.bisect_right(bands, (days, float("inf"))) - 1 if index < 0: raise ValueError(f"no fee band co...
from solution import claim_fee, describe_claim, lookup_fee_rate def test_lookup_picks_latest_band() -> None: bands = [(0, 0.0), (30, 0.05), (365, 0.2)] assert lookup_fee_rate(bands, 100) == 0.05 assert lookup_fee_rate(bands, 30) == 0.05 assert lookup_fee_rate(bands, 365) == 0.2 def test_lookup_below...
from solution import FeeBand, claim_fee, describe_claim, lookup_fee_rate BANDS: list[FeeBand] = [(0, 0.1), (30, 0.25), (90, 0.5)] def test_lookup_picks_largest_threshold_at_or_below() -> None: assert lookup_fee_rate(BANDS, 0) == 0.1 assert lookup_fee_rate(BANDS, 29) == 0.1 assert lookup_fee_rate(BANDS, 3...
glm-5.3-flash
import bisect from typing import List, Tuple FeeBand = Tuple[int, float] def lookup_fee_rate(bands: List[FeeBand], days: int) -> float: """Return the rate of the band with the largest threshold at or below days.""" index = bisect.bisect_right(bands, (days, float("inf"))) - 1 if index < 0: raise V...
{ "mutant": "import bisect\ntype FeeBand = tuple[int, float]\n\ndef lookup_fee_rate(bands: list[FeeBand], days: int) -> float:\n \"\"\"Return the rate of the band with the largest threshold at or below days.\"\"\"\n index = bisect.bisect_right(bands, (days, float('inf'))) - 1\n if index < 1:\n raise V...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-57937d7e4408f37c
code
async_basics
py
function
1
short
{ "kind": "legal", "text": "Examination of international design application (the subject of 35 U.S.C. 389, Patents)", "sources": [ { "source": "usc", "id": "35 U.S.C. 389" } ] }
ds-v4.1-flash
Write an async module that models the examination of an international design application under 35 U.S.C. 389. Provide `async def run_stage(application_id: str, stage: str, delay: float) -> str` and `def examine(application_id: str, stages: list[tuple[str, float]]) -> list[str]`. `run_stage` awaits `asyncio.sleep(delay)...
[ "Define `run_stage` as an async function that sleeps for the given delay.", "Build the label from the application id and stage name.", "Inside `examine`, define a nested async function that returns `[]` for an empty stage list.", "Otherwise gather all stage coroutines and await them.", "Run the nested funct...
import asyncio async def run_stage(application_id: str, stage: str, delay: float) -> str: """Run one examination stage after a fixed delay and return its outcome.""" await asyncio.sleep(delay) return f"{application_id}/{stage}:ok" def examine(application_id: str, stages: list[tuple[str, float]]) -> list...
import asyncio from solution import examine, run_stage def test_stage_returns_label() -> None: assert asyncio.run(run_stage("D-7", "search", 0.0)) == "D-7/search:ok" def test_examine_preserves_order() -> None: stages = [("formalities", 0.0), ("search", 0.0), ("report", 0.0)] result = examine("D-7", sta...
from solution import examine, run_stage def test_run_stage_label() -> None: assert examine("A1", []) == [] def test_run_stage_returns_label() -> None: async def check() -> str: return await run_stage("A1", "search", 0.0) assert examine("A1", [("search", 0.0)]) == ["A1/search:ok"] def test_exa...
glm-5.3-flash
import asyncio from typing import List, Tuple async def run_stage(application_id: str, stage: str, delay: float) -> str: """Run one examination stage after a fixed delay and return its outcome.""" await asyncio.sleep(delay) return "{0}/{1}:ok".format(application_id, stage) def examine(application_id: st...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [], "b...
ol5-98424ffa1f2c79a5
code
hashable_value
py
module
2
short
{ "kind": "topic", "text": "swad (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:swad", "headword": "swad" } ] }
ds-v4.1-flash
Here is a small module about swad, the everyday handover of a shared toolbox between neighbouring flats. Write a frozen `SwadTurn` dataclass with fields `holder: str` and `week: int`, and three functions: `distinct_turns(turns: list[SwadTurn]) -> set[SwadTurn]`, `tally_turns(turns: list[SwadTurn]) -> dict[SwadTurn, int...
[ "Define `SwadTurn` as a frozen slots dataclass, which gives value equality and a hash.", "Collapse a turn list through `set` for `distinct_turns`.", "Count with `dict.get` for `tally_turns`, and read the roster with `dict.get` for `note_for`." ]
"""Swad: the handover of a shared toolbox between neighbouring flats.""" from dataclasses import dataclass @dataclass(frozen=True, slots=True) class SwadTurn: """One handover: a holder keeps the shared toolbox for a numbered week.""" holder: str week: int def distinct_turns(turns: list[SwadTurn]) -> s...
from solution import SwadTurn, distinct_turns, note_for, tally_turns def test_equal_fields_make_equal_turns() -> None: assert SwadTurn(holder="Ada", week=3) == SwadTurn(holder="Ada", week=3) assert hash(SwadTurn(holder="Ada", week=3)) == hash(SwadTurn(holder="Ada", week=3)) def test_different_week_is_a_diff...
from solution import SwadTurn, distinct_turns, note_for, tally_turns def test_equal_turns_equal_and_hash_same() -> None: a = SwadTurn(holder="ana", week=3) b = SwadTurn(holder="ana", week=3) assert a == b assert hash(a) == hash(b) def test_distinct_turns_collapses_equal_pairs() -> None: turns = ...
glm-5.3-flash
"""Swad: the handover of a shared toolbox between neighbouring flats.""" from typing import Dict, List, Optional, Set class SwadTurn: """One handover: a holder keeps the shared toolbox for a numbered week.""" def __init__(self, holder: str, week: int) -> None: self.holder = holder self.week ...
{ "mutant": "\"\"\"Swad: the handover of a shared toolbox between neighbouring flats.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass SwadTurn:\n \"\"\"One handover: a holder keeps the shared toolbox for a numbered week.\"\"\"\n holder: str\n week: int\n\ndef distinct_t...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining"...
ol5-c750afbc5ae105a5
code
enum_auto
py
enum_plus_fn
1
short
{ "kind": "legal", "text": "Fiscal period (the subject of 7 CFR 945.12, Agriculture)", "sources": [ { "source": "ecfr", "id": "7 CFR 945.12", "agency": "AGRICULTURAL MARKETING SERVICE (MARKETING AGREEMENTS AND ORDERS; FRUITS, VEGETABLES, NUTS), DEPARTMENT OF AGRICULTURE" } ] }
ds-v4.1-flash
For a farm payment notice, write `FiscalPeriod` and `period_label`. `FiscalPeriod` is an `Enum` with four members `FIRST`, `SECOND`, `THIRD`, and `FOURTH`, created with `enum.auto()`. It has a classmethod `from_month(cls, month: int) -> FiscalPeriod` that maps calendar months to fiscal quarters: October through Decembe...
[ "Define `FiscalPeriod` with four `auto()` members.", "Add `from_month`, validating the month and returning the right member.", "Add `period_label`, choosing the quarter text from the member.", "Format and return the fiscal year label." ]
from enum import Enum, auto class FiscalPeriod(Enum): """A quarter of the federal fiscal year.""" FIRST = auto() SECOND = auto() THIRD = auto() FOURTH = auto() @classmethod def from_month(cls, month: int) -> FiscalPeriod: """Return the fiscal period containing a calendar month.""...
from solution import FiscalPeriod, period_label def test_first_period_covers_october() -> None: assert FiscalPeriod.from_month(10) == FiscalPeriod.FIRST def test_second_period_covers_january() -> None: assert FiscalPeriod.from_month(1) == FiscalPeriod.SECOND def test_third_period_covers_april() -> None: ...
from solution import FiscalPeriod, period_label def test_members_exist() -> None: assert [p.name for p in FiscalPeriod] == ["FIRST", "SECOND", "THIRD", "FOURTH"] def test_october_to_december_is_first() -> None: for month in (10, 11, 12): assert FiscalPeriod.from_month(month) is FiscalPeriod.FIRST ...
glm-5.3-flash
class FiscalPeriod: """A quarter of the federal fiscal year.""" FIRST = 1 SECOND = 2 THIRD = 3 FOURTH = 4 @classmethod def from_month(cls, month: int) -> int: """Return the fiscal period number containing a calendar month.""" if month < 1 or month > 12: raise Va...
{ "mutant": "from enum import Enum, auto\n\nclass FiscalPeriod(Enum):\n \"\"\"A quarter of the federal fiscal year.\"\"\"\n FIRST = auto()\n SECOND = auto()\n THIRD = auto()\n FOURTH = auto()\n\n @classmethod\n def from_month(cls, month: int) -> FiscalPeriod:\n \"\"\"Return the fiscal peri...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-769749a85e04ab97
code
dp_lis
alg
module
2
short
{ "kind": "og", "text": "tonguefish (A common name for marine flatfishes in the family Cynoglossidae, typically small, dorsoventrally flattened, with eyes on the left side)", "sources": [ { "source": "opengloss", "id": "og-glossary:tonguefish", "headword": "tonguefish" } ] }
ds-v4.1-flash
A tonguefish survey records body lengths in the order the fish were measured. Write `longest_increasing(values: list[int]) -> int` and `tail_slots(values: list[int]) -> list[int]`. `longest_increasing` returns the length of the longest strictly increasing subsequence of the measurements. `tail_slots` returns the final ...
[ "Scan each measurement with a tails list.", "Use `bisect_left` to find the first tail that is not smaller.", "Replace that tail or append the measurement when no such tail exists.", "Return the tails array, and return its length for the LIS size." ]
from bisect import bisect_left def tail_slots(values: list[int]) -> list[int]: """Return the patience-sorting tails after scanning values.""" tails: list[int] = [] for value in values: index = bisect_left(tails, value) if index == len(tails): tails.append(value) else: ...
from solution import longest_increasing, tail_slots def test_empty_samples_have_zero_length() -> None: assert longest_increasing([]) == 0 assert tail_slots([]) == [] def test_duplicate_samples_are_not_increasing() -> None: assert longest_increasing([3, 3, 3]) == 1 assert tail_slots([3, 3, 3]) == [3]...
from solution import longest_increasing, tail_slots def test_empty_input() -> None: assert longest_increasing([]) == 0 assert tail_slots([]) == [] def test_single_value() -> None: assert longest_increasing([5]) == 1 assert tail_slots([5]) == [5] def test_strictly_increasing_all() -> None: asse...
glm-5.3-flash
from bisect import bisect_left from typing import List def tail_slots(values: List[int]) -> List[int]: """Return the patience-sorting tails after scanning values.""" tails: List[int] = [] i = 0 while i < len(values): value = values[i] index = bisect_left(tails, value) if index ...
{ "mutant": "from bisect import bisect_left\n\ndef tail_slots(values: list[int]) -> list[int]:\n \"\"\"Return the patience-sorting tails after scanning values.\"\"\"\n tails: list[int] = []\n for value in values:\n index = bisect_left(tails, value)\n if index != len(tails):\n tails.a...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-1087ca91349a43f9
code
graphlib
py
generator
3
short
{ "kind": "og", "text": "duckbills (The broad flattened beak of ducks and related waterfowl, adapted for surface feeding and filter-feeding)", "sources": [ { "source": "opengloss", "id": "og-glossary:duckbills", "headword": "duckbills" } ] }
ds-v4.1-flash
Could you write a small module that orders duckbill trait checks by what each check depends on? I need a generator `iter_trait_order(prerequisites: dict[str, list[str]]) -> Iterator[tuple[str, int]]` that yields each trait together with its dependency layer, and a consumer `summarize_order(prerequisites: dict[str, list...
[ "Collect the key set and check every prerequisite name against it, raising `ValueError` on the first unknown name.", "Hand the mapping to `graphlib.TopologicalSorter` and call `prepare()`.", "While the sorter is active, take the ready set, sort it, yield each trait with the current layer, then mark all of them ...
import graphlib from collections.abc import Iterator def iter_trait_order(prerequisites: dict[str, list[str]]) -> Iterator[tuple[str, int]]: """Yield each duckbill trait with the layer it can be checked in.""" known = set(prerequisites) for trait, needs in prerequisites.items(): for need in needs:...
import graphlib from solution import iter_trait_order, summarize_order def test_empty_input_yields_nothing() -> None: assert summarize_order({}) == [] def test_layers_start_at_zero() -> None: prereq = {"bill width": [], "lamellae count": [], "filter rate": ["bill width"]} assert summarize_order(prereq)...
import graphlib from solution import iter_trait_order, summarize_order def test_simple_two_layers() -> None: order = list(iter_trait_order({"bill width": [], "tail: bill width": ["bill width"]})) assert dict(order) == {"bill width": 0, "tail: bill width": 1} def test_all_zero_layer() -> None: order = l...
glm-5.3-flash
import graphlib from typing import Dict, Iterator, List, Tuple def iter_trait_order( prerequisites: Dict[str, List[str]], ) -> Iterator[Tuple[str, int]]: """Yield each duckbill trait with the layer it can be checked in.""" known = set(prerequisites.keys()) for trait in prerequisites.keys(): fo...
{ "mutant": "import graphlib\nfrom collections.abc import Iterator\n\ndef iter_trait_order(prerequisites: dict[str, list[str]]) -> Iterator[tuple[str, int]]:\n \"\"\"Yield each duckbill trait with the layer it can be checked in.\"\"\"\n known = set(prerequisites)\n for trait, needs in prerequisites.items():\...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining"...
ol5-b48ffbe0ab327374
code
reservoir_free_stats
alg
function
3
short
{ "kind": "og", "text": "phones (A device for voice communication over a telecommunications network)", "sources": [ { "source": "opengloss", "id": "og-glossary:phones", "headword": "phones" } ] }
ds-v4.1-flash
Our call log reader hands out one shot of talk times and we cannot afford to keep the whole day in memory. Please write `call_span_stats(durations: Iterable[int]) -> tuple[int, int, float]`, which reads the iterable once and returns the shortest talk time, the longest talk time and the mean talk time as a float. Rule 1...
[ "Keep a running total, a count, and optional lowest and highest values.", "Walk the iterable once; on a negative value raise `ValueError` straight away.", "Update the total, the count, and the two extremes for each value.", "After the loop, raise `ValueError` if nothing arrived, otherwise return the extremes ...
from collections.abc import Iterable def call_span_stats(durations: Iterable[int]) -> tuple[int, int, float]: """Return minimum, maximum and mean talk time from a single pass.""" total = 0 count = 0 lowest: int | None = None highest: int | None = None for seconds in durations: if secon...
from collections.abc import Iterator from solution import call_span_stats def _stream(values: list[int]) -> Iterator[int]: yield from values def test_single_pass_over_one_shot_iterator() -> None: assert call_span_stats(_stream([120, 30, 90, 60])) == (30, 120, 75.0) def test_one_call() -> None: assert...
from collections.abc import Iterator from solution import call_span_stats def test_basic_stats() -> None: assert call_span_stats([3, 1, 2]) == (1, 3, 2.0) def test_single_value() -> None: assert call_span_stats([5]) == (5, 5, 5.0) def test_empty_raises() -> None: try: call_span_stats(iter([])...
glm-5.3-flash
from typing import Iterable, Optional, Tuple def call_span_stats(durations: Iterable[int]) -> Tuple[int, int, float]: """Return minimum, maximum and mean talk time from a single pass.""" total = 0 count = 0 lowest: Optional[int] = None highest: Optional[int] = None for seconds in durations: ...
{ "mutant": "from collections.abc import Iterable\n\ndef call_span_stats(durations: Iterable[int]) -> tuple[int, int, float]:\n \"\"\"Return minimum, maximum and mean talk time from a single pass.\"\"\"\n total = 0\n count = 1\n lowest: int | None = None\n highest: int | None = None\n for seconds in...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-2310d3d712222f73
code
heapq_keyed
py
module
1
short
{ "kind": "legal", "text": "Permits, leases, or easements; authorization to grant; payment; limitation (the subject of 43 U.S.C. 931c, Public Lands)", "sources": [ { "source": "usc", "id": "43 U.S.C. 931c" } ] }
ds-v4.1-flash
We review land permits and easement requests, and reviewers must see equal-priority filings in the order they arrived. Please write a module with `push_application(heap: list[tuple[int, int, str]], tickets: Iterator[int], permit_id: str, priority: int) -> None`, which pushes one filing onto a list used as a heap, and `...
[ "Push `(priority, next(tickets), permit_id)` with `heapq.heappush`, so the counter is compared before the name.", "Drain with `heapq.heappop` in a loop, appending `(permit_id, priority)`.", "Return the ordered list, leaving the heap empty." ]
import heapq from collections.abc import Iterator def push_application( heap: list[tuple[int, int, str]], tickets: Iterator[int], permit_id: str, priority: int, ) -> None: """Push one permit application onto the review heap, keeping arrival order for ties.""" heapq.heappush(heap, (priority, ne...
import itertools from solution import drain_applications, push_application def _heap_with(entries: list[tuple[str, int]]) -> list[tuple[int, int, str]]: heap: list[tuple[int, int, str]] = [] tickets = itertools.count() for permit_id, priority in entries: push_application(heap, tickets, permit_id,...
from itertools import count from solution import drain_applications, push_application def test_push_and_drain_by_priority() -> None: heap: list[tuple[int, int, str]] = [] tickets = count() push_application(heap, tickets, "p1", 3) push_application(heap, tickets, "p2", 1) push_application(heap, tic...
glm-5.3-flash
import heapq from typing import Iterator, List, Tuple def push_application( heap: List[Tuple[int, int, str]], tickets: Iterator[int], permit_id: str, priority: int, ) -> None: """Push one permit application onto the review heap, keeping arrival order for ties.""" heapq.heappush(heap, (priority...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-c48b950b22f4188c
code
async_basics
py
class
2
short
{ "kind": "public", "text": "interest rate resets", "sources": [] }
ds-v4.1-flash
Write a small async module for projecting balances through interest rate resets. Provide a class `RateLedger` with fields `balance: float` and `rate: float`, an async method `accrue(self, months: int) -> float` that compounds the balance monthly at the ledger rate, an async method `project(self, targets: list[float], m...
[ "Model the ledger as a slotted dataclass holding balance and rate.", "Compound in `accrue`, rejecting negative month counts.", "Validate targets in `project`, build one ledger per target, and gather the coroutines in order.", "Gather the current projection and the target batch in `reset_report`, then expose `...
"""Async projections for an interest rate reset ledger.""" from __future__ import annotations import asyncio from dataclasses import dataclass @dataclass(slots=True) class RateLedger: """A balance that compounds monthly at a fixed nominal rate.""" balance: float rate: float async def accrue(self, ...
import asyncio from solution import RateLedger, reset_report, run_reset_report def test_accrue_compounds_monthly() -> None: ledger = RateLedger(balance=200.0, rate=0.01) result = asyncio.run(ledger.accrue(2)) assert abs(result - 200.0 * 1.01 * 1.01) < 1e-9 def test_accrue_rejects_negative_months() -> N...
import asyncio from solution import RateLedger, run_reset_report def test_accrue_negative_months() -> None: async def go() -> None: ledger = RateLedger(balance=100.0, rate=0.1) try: await ledger.accrue(-1) except ValueError: pass else: raise Ass...
glm-5.3-flash
"""Async projections for an interest rate reset ledger.""" import asyncio from typing import List, Tuple class RateLedger(object): """A balance that compounds monthly at a fixed nominal rate.""" def __init__(self, balance: float, rate: float) -> None: self.balance = balance self.rate = rate ...
{ "mutant": "\"\"\"Async projections for an interest rate reset ledger.\"\"\"\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass RateLedger:\n \"\"\"A balance that compounds monthly at a fixed nominal rate.\"\"\"\n balance: float\n rate: fl...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-cad5e704ed8f2820
code
matrix_ops
alg
pure_pipeline
5
short
{ "kind": "og", "text": "leafhopper (A small, agile sap-sucking insect of the family Cicadellidae, commonly a crop pest and vector of plant pathogens)", "sources": [ { "source": "opengloss", "id": "og-glossary:leafhopper", "headword": "leafhopper" } ] }
ds-v4.1-flash
We score leafhopper sweep-net counts per plot and per day, and we want a small grid toolkit that tells us how pressure spreads between plots. Provide `add_matrices(left: Matrix, right: Matrix) -> Matrix`, `multiply_matrices(left: Matrix, right: Matrix) -> Matrix` and a pipeline `project_pressure(nymphs: Matrix, adults:...
[ "Validate rectangularity with one helper used by both arithmetic functions.", "Add with matching shape checks and element-wise sums.", "Multiply by transposing the right matrix into columns and taking row-by-column products.", "Short-circuit to `[]` when either side has no rows.", "In the pipeline, reject n...
"""Grid arithmetic for leafhopper sweep-net counts.""" type Matrix = list[list[int]] def _check_rectangular(matrix: Matrix) -> None: """Raise ValueError unless every row has the same length as the first.""" if matrix: width = len(matrix[0]) for row in matrix: if len(row) != width:...
from solution import add_matrices, multiply_matrices, project_pressure def test_add_matrices_sums_elementwise_and_keeps_inputs() -> None: left = [[1, 2], [3, 4]] right = [[10, 20], [30, 40]] assert add_matrices(left, right) == [[11, 22], [33, 44]] assert left == [[1, 2], [3, 4]] assert right == [[...
from solution import ( Matrix, add_matrices, multiply_matrices, project_pressure, ) def test_add_elementwise() -> None: left: Matrix = [[1, 2], [3, 4]] right: Matrix = [[10, 20], [30, 40]] assert add_matrices(left, right) == [[11, 22], [33, 44]] def test_add_empty() -> None: assert a...
glm-5.3-flash
"""Grid arithmetic for leafhopper counts, older style.""" from typing import List Matrix = List[List[int]] def _check_rectangular(matrix): # type: (Matrix) -> None if len(matrix) == 0: return width = len(matrix[0]) for row in matrix: if len(row) != width: raise ValueError...
{ "mutant": "\"\"\"Grid arithmetic for leafhopper sweep-net counts.\"\"\"\ntype Matrix = list[list[int]]\n\ndef _check_rectangular(matrix: Matrix) -> None:\n \"\"\"Raise ValueError unless every row has the same length as the first.\"\"\"\n if matrix:\n width = len(matrix[1])\n for row in matrix:\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "re...
ol5-30a7bc3416eaba0c
code
pathlib
py
module
2
short
{ "kind": "og", "text": "deedbox (a strongly made box for holding money or valuables)", "sources": [ { "source": "opengloss", "id": "og-glossary:deedbox", "headword": "deedbox" } ] }
ds-v4.1-flash
A deedbox is a small directory of legal documents, and I need three helpers for it. Write `list_deeds(box: Path) -> list[str]`, `deed_paths(box: Path) -> list[Path]` and `total_words(box: Path) -> int`. `list_deeds` returns the names of the deed files directly inside `box`, sorted; `deed_paths` returns their full paths...
[ "Check with `is_dir` and raise `FileNotFoundError` when the check fails.", "Collect the names of files directly inside the directory whose suffix is `.deed`.", "Sort the names and return them.", "Build full paths by joining the directory with each name.", "Read each deed as UTF-8 text and add its word count...
from pathlib import Path def _check(box: Path) -> None: if not box.is_dir(): raise FileNotFoundError(box) def list_deeds(box: Path) -> list[str]: """Return the sorted names of the deed files directly inside box.""" _check(box) return sorted( entry.name for entry in box.iterdir() if e...
import tempfile from pathlib import Path from solution import deed_paths, list_deeds, total_words def _make_box(root: Path) -> Path: box = root / "deedbox" box.mkdir() (box / "lease.deed").write_text("alpha beta gamma", encoding="utf-8") (box / "title.deed").write_text("delta", encoding="utf-8") ...
import tempfile from pathlib import Path from solution import deed_paths, list_deeds, total_words def _make_box() -> Path: box = Path(tempfile.mkdtemp()) (box / "b.deed").write_text("two words here") (box / "a.deed").write_text("one") (box / "notes.txt").write_text("ignored words") sub = box / "s...
glm-5.3-flash
null
{ "mutant": "from pathlib import Path\n\ndef _check(box: Path) -> None:\n if not box.is_dir():\n raise FileNotFoundError(box)\n\ndef list_deeds(box: Path) -> list[str]:\n \"\"\"Return the sorted names of the deed files directly inside box.\"\"\"\n _check(box)\n return sorted((entry.name for entry i...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, ...
ol5-19c4d959f767385d
code
type_narrowing
py
validator
1
short
{ "kind": "topic", "text": "olive-colored (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:olive-colored", "headword": "olive-colored" } ] }
ds-v4.1-flash
We keep olive tones for a paint catalogue in three shapes: a channel tuple, a name, or nothing at all. Declare `type Rgb = tuple[int, ...]` and `type OliveTone = Rgb | str | None`, then write `tone_problems(tone: OliveTone) -> list[str]` that returns one message per problem, and an empty list when the tone is acceptabl...
[ "Branch on `isinstance(tone, tuple)` so the checker narrows the union.", "Inside the tuple branch, check length, channel range and green against red in that order.", "Branch on `isinstance(tone, str)` for names.", "Fall through to `None`." ]
"""Checks for olive tones used in a paint catalogue.""" type Rgb = tuple[int, ...] type OliveTone = Rgb | str | None CHANNEL_MIN = 0 CHANNEL_MAX = 255 TRIPLE_LENGTH = 3 def tone_problems(tone: OliveTone) -> list[str]: """Return the problems of one olive tone description, empty when acceptable.""" if isinsta...
from solution import tone_problems def test_acceptable_tone() -> None: assert tone_problems((100, 140, 60)) == [] def test_missing_tone() -> None: assert tone_problems(None) == ["tone is missing"] def test_name_is_not_a_triple() -> None: assert tone_problems("dark olive") == ["tone name 'dark olive' i...
from solution import tone_problems def test_acceptable_triples() -> None: assert tone_problems((0, 0, 0)) == [] assert tone_problems((255, 255, 255)) == [] assert tone_problems((10, 10, 20)) == [] def test_wrong_length() -> None: assert tone_problems((1, 2)) == ["channel triple has 2 values, expecte...
glm-5.3-flash
"""Checks for olive tones used in a paint catalogue.""" from typing import List, Optional, Tuple, Union Rgb = Tuple[int, ...] OliveTone = Union[Rgb, str, None] CHANNEL_MIN = 0 CHANNEL_MAX = 255 TRIPLE_LENGTH = 3 def tone_problems(tone: OliveTone) -> List[str]: """Return the problems of one olive tone descripti...
{ "mutant": "\"\"\"Checks for olive tones used in a paint catalogue.\"\"\"\ntype Rgb = tuple[int, ...]\ntype OliveTone = Rgb | str | None\nCHANNEL_MIN = 0\nCHANNEL_MAX = 255\nTRIPLE_LENGTH = 3\n\ndef tone_problems(tone: OliveTone) -> list[str]:\n \"\"\"Return the problems of one olive tone description, empty when ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b...
ol5-b1cb125d48556ff0
code
parametrized_cases
test
class
3
short
{ "kind": "og", "text": "thermograph (An instrument that automatically records temperature as a function of time)", "sources": [ { "source": "opengloss", "id": "og-glossary:thermograph", "headword": "thermograph" } ] }
glm-5.3-flash
I need a small thermograph recorder for a greenhouse controller. Write a class `Thermograph` with `record(self, minute: int, celsius: float) -> None`, `reading_at(self, minute: int) -> float | None`, and `stable_run(self, lo: float, hi: float) -> int | None`. `record` stores one reading per minute. `reading_at` returns...
[ "Keep readings in a dict[int, float]; check for duplicates in `record`.", "`reading_at` is a plain dict lookup returning `None` on miss.", "Sort recorded minutes, walk them, extend a run while adjacent and in window, track the maximum.", "Table of (input, expected) cases drives the tests in a single loop." ]
"""A greenhouse thermograph that records temperatures by minute.""" class Thermograph: """Records one temperature reading per minute and answers window queries.""" def __init__(self) -> None: self._readings: dict[int, float] = {} def record(self, minute: int, celsius: float) -> None: """...
from solution import Thermograph def test_reading_at() -> None: t = Thermograph() t.record(3, 21.5) assert t.reading_at(3) == 21.5 assert t.reading_at(4) is None def test_duplicate_minute_raises() -> None: t = Thermograph() t.record(1, 20.0) try: t.record(1, 21.0) except Valu...
from solution import Thermograph def test_record_and_read() -> None: thermo = Thermograph() thermo.record(5, 20.5) assert thermo.reading_at(5) == 20.5 def test_unrecorded_minute_returns_none() -> None: thermo = Thermograph() thermo.record(1, 10.0) assert thermo.reading_at(2) is None def te...
ds-v4.1-flash
"""A greenhouse thermograph that records temperatures by minute.""" class Thermograph(object): """Records one temperature reading per minute and answers window queries.""" def __init__(self): self._readings = {} def record(self, minute, celsius): """Store one reading; each minute may be ...
{ "mutant": "\"\"\"A greenhouse thermograph that records temperatures by minute.\"\"\"\n\nclass Thermograph:\n \"\"\"Records one temperature reading per minute and answers window queries.\"\"\"\n\n def __init__(self) -> None:\n self._readings: dict[int, float] = {}\n\n def record(self, minute: int, ce...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-fefbd163980eb345
code
topological_sort
alg
enum_plus_fn
4
short
{ "kind": "legal", "text": "Form of application (the subject of 7 CFR 51.7, Agriculture)", "sources": [ { "source": "ecfr", "id": "7 CFR 51.7", "agency": "AGRICULTURAL MARKETING SERVICE (STANDARDS, INSPECTIONS, MARKETING PRACTICES), DEPARTMENT OF AGRICULTURE" } ] }
glm-5.3-flash
Our permits office processes applications; each application form belongs to one category. Write an enum `FormKind` with members `SOIL_TEST = "soil_test"`, `ORGANIC_INPUT = "organic_input"`, `INSPECTION = "inspection"`, and a function `submission_order(kinds: list[FormKind]) -> list[FormKind]` that returns the kinds in ...
[ "Store prerequisites in a dict keyed by FormKind; duplicate check via a set.", "Build in-degree counts over the dependency edges.", "Seed a queue with zero in-degree kinds and peel them off in Kahn style.", "If fewer than all kinds were emitted, raise the cycle error; otherwise return the order." ]
"""Submission ordering for agricultural application forms.""" from enum import Enum class FormKind(Enum): """Categories of application forms handled by the permits office.""" SOIL_TEST = "soil_test" ORGANIC_INPUT = "organic_input" INSPECTION = "inspection" _REQUIRES: dict[FormKind, frozenset[FormK...
from solution import FormKind, submission_order def test_full_order() -> None: result = submission_order([FormKind.INSPECTION, FormKind.ORGANIC_INPUT, FormKind.SOIL_TEST]) assert result[0] == FormKind.SOIL_TEST assert result[-1] == FormKind.ORGANIC_INPUT assert len(result) == 3 def test_every_kind_o...
from solution import FormKind, submission_order def test_enum_values() -> None: assert FormKind.SOIL_TEST.value == "soil_test" assert FormKind.ORGANIC_INPUT.value == "organic_input" assert FormKind.INSPECTION.value == "inspection" def test_all_kinds_in_dependency_order() -> None: result = submission...
ds-v4.1-flash
"""Submission ordering for agricultural application forms.""" from enum import Enum class FormKind(Enum): """Categories of application forms handled by the permits office.""" SOIL_TEST = "soil_test" ORGANIC_INPUT = "organic_input" INSPECTION = "inspection" _REQUIRES = { FormKind.SOIL_TEST: fro...
{ "mutant": "\"\"\"Submission ordering for agricultural application forms.\"\"\"\nfrom enum import Enum\n\nclass FormKind(Enum):\n \"\"\"Categories of application forms handled by the permits office.\"\"\"\n SOIL_TEST = 'soil_test'\n ORGANIC_INPUT = 'organic_input'\n INSPECTION = 'inspection'\n_REQUIRES: ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-b169863ddde89d95
code
two_pointer
alg
enum_plus_fn
3
short
{ "kind": "og", "text": "dormitory (An on campus building designed to house students, providing residential accommodations for enrolled students)", "sources": [ { "source": "opengloss", "id": "og-glossary:dormitory", "headword": "dormitory" } ] }
glm-5.3-flash
A dormitory has two wings and I need to bed students into rooms automatically. Write an enum `Wing` with members `EAST` and `WEST`, a function `bed_capacity(wing: Wing, base: int) -> int` that dispatches on the wing (EAST rooms hold `base` beds, WEST rooms hold `base + 1`), and a function `match_beds(rooms: list[int], ...
[ "Dispatch on the `Wing` member to build the capacity list from the room bases.", "Validate that both lists are ascending and that there are enough rooms.", "Walk the requests with a pointer over rooms; advance the room pointer past rooms that are too small.", "Assign each request to the current room and move ...
from enum import Enum, auto class Wing(Enum): """Dormitory wings with different room sizing.""" EAST = auto() WEST = auto() def bed_capacity(wing: Wing, base: int) -> int: """Return the number of beds a room with the given base size holds in the wing.""" match wing: case Wing.EAST: ...
from solution import Wing, bed_capacity, match_beds def test_capacity_dispatch() -> None: assert bed_capacity(Wing.EAST, 4) == 4 assert bed_capacity(Wing.WEST, 4) == 5 def test_simple_matching() -> None: assert match_beds([1, 2, 2, 3], [1, 2, 3], wing=Wing.EAST) == {0: 0, 1: 1, 2: 3} def test_west_roo...
from solution import Wing, bed_capacity, match_beds def test_bed_capacity_dispatches_on_wing() -> None: assert bed_capacity(Wing.EAST, 4) == 4 assert bed_capacity(Wing.WEST, 4) == 5 def test_bed_capacity_with_zero_base() -> None: assert bed_capacity(Wing.EAST, 0) == 0 assert bed_capacity(Wing.WEST, ...
ds-v4.1-flash
from enum import Enum, auto class Wing(Enum): """Dormitory wings with different room sizing.""" EAST = auto() WEST = auto() def bed_capacity(wing, base): # type: (Wing, int) -> int """Return the number of beds a room with the given base size holds in the wing.""" if wing is Wing.EAST: ...
{ "mutant": "from enum import Enum, auto\n\nclass Wing(Enum):\n \"\"\"Dormitory wings with different room sizing.\"\"\"\n EAST = auto()\n WEST = auto()\n\ndef bed_capacity(wing: Wing, base: int) -> int:\n \"\"\"Return the number of beds a room with the given base size holds in the wing.\"\"\"\n match w...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": fals...
ol5-8f7e336eeadbf4d5
code
operator_module
py
stateful_class
4
short
{ "kind": "og", "text": "depositary (A person who receives and safely keeps deposits for others, such as money or valuables)", "sources": [ { "source": "opengloss", "id": "og-glossary:depositary", "headword": "depositary" } ] }
glm-5.3-flash
I keep valuables for neighbours and need a small ledger. Write a dataclass `Holding(owner: str, balance: int)` with `slots=True` and a class `Depositary` with `__init__(self) -> None`, `deposit(self, owner: str, amount: int) -> None`, `withdraw(self, owner: str, amount: int) -> None`, and `summary(self) -> list[Holding...
[ "Keep balances in a private `dict[str, int]`.", "Validate amounts in `deposit` and `withdraw` and raise the specified errors.", "In `summary`, build `Holding` objects for every owner.", "Sort first by owner name ascending, then stably by balance descending, using `attrgetter`." ]
from dataclasses import dataclass from operator import attrgetter @dataclass(slots=True) class Holding: """One owner's stored balance.""" owner: str balance: int class Depositary: """Keeps a balance for each owner and reports a sorted summary.""" def __init__(self) -> None: self._balan...
from solution import Depositary, Holding def test_deposit_accumulates() -> None: d = Depositary() d.deposit("ana", 100) d.deposit("ana", 50) assert d.summary() == [Holding("ana", 150)] def test_negative_deposit_rejected() -> None: d = Depositary() try: d.deposit("ana", -1) except...
from solution import Depositary, Holding def test_negative_deposit_raises() -> None: depositary = Depositary() try: depositary.deposit("alice", -1) except ValueError: pass else: raise AssertionError("negative deposit did not raise") assert depositary.summary() == [] def t...
ds-v4.1-flash
from operator import attrgetter class Holding(object): """One owner's stored balance.""" def __init__(self, owner, balance): # type: (str, int) -> None self.owner = owner self.balance = balance def __repr__(self): return "Holding(owner={!r}, balance={!r})".format(self.own...
{ "mutant": "from dataclasses import dataclass\nfrom operator import attrgetter\n\n@dataclass(slots=True)\nclass Holding:\n \"\"\"One owner's stored balance.\"\"\"\n owner: str\n balance: int\n\nclass Depositary:\n \"\"\"Keeps a balance for each owner and reports a sorted summary.\"\"\"\n\n def __init_...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b...
ol5-dbc66a279c45af78
code
slots_class
py
generator
6
short
{ "kind": "legal", "text": "Application of other Commission rules (the subject of 19 CFR 220.15, Customs Duties)", "sources": [ { "source": "ecfr", "id": "19 CFR 220.15", "agency": "UNITED STATES INTERNATIONAL TRADE COMMISSION" } ] }
glm-5.3-flash
For an internal review of how our brokerage applies other Commission rules to declared entries, write a module with one class and two functions. `class Entry` holds a `ref: str`, a `value: float` and a `formal: bool`, defines `__slots__`, and its `__repr__` renders exactly as `Entry(ref='E1', value=300.0, formal=True)`...
[ "`Entry` stores its three fields via `__slots__` and formats its own repr.", "`iter_dutiable` loops over entries, raises `ValueError` on a negative value when reached, then applies the threshold and formal filters.", "`total_duty` iterates the generator, charges each yielded entry by its formality rate, and rou...
"""Review declared customs entries and total the duty they attract.""" from collections.abc import Iterator, Sequence RATE_FORMAL = 0.06 RATE_INFORMAL = 0.025 class Entry: """A single declared customs entry.""" __slots__ = ("formal", "ref", "value") def __init__(self, ref: str, value: float, formal: b...
from solution import Entry, iter_dutiable, total_duty def _entries() -> list[Entry]: return [ Entry("E1", 300.0, True), Entry("E2", 100.0, True), Entry("E3", 400.0, False), ] def test_repr() -> None: assert repr(Entry("E1", 300.0, True)) == "Entry(ref='E1', value=300.0, formal=Tr...
from solution import Entry, iter_dutiable, total_duty def test_entry_repr_is_exact() -> None: assert repr(Entry("E1", 300.0, True)) == "Entry(ref='E1', value=300.0, formal=True)" def test_entry_uses_slots() -> None: entry = Entry("E1", 1.0, True) assert not hasattr(entry, "__dict__") def test_iter_dut...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Review declared customs entries and total the duty they attract.\"\"\"\nfrom collections.abc import Iterator, Sequence\nRATE_FORMAL = 0.06\nRATE_INFORMAL = 0.025\n\nclass Entry:\n \"\"\"A single declared customs entry.\"\"\"\n __slots__ = ('formal', 'ref', 'value')\n\n def __init__(self, r...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-f392dd695ecc6296
code
custom_merge_sort
alg
generator
3
short
{ "kind": "public", "text": "weather station logs", "sources": [] }
glm-5.3-flash
Our weather station stores a day log as `(date_tag, temperature)` pairs, and I need to know how "unstable" a week was. Write `inversion_pairs(temps: list[float]) -> Iterator[tuple[int, int]]`, a generator that runs a merge sort over the indices and yields every pair `(i, j)` with `i < j` but `temps[i] > temps[j]`. Then...
[ "Keep an index order list; recursively merge-sort ranges of it.", "During each merge, when a right-side index comes first, yield pairs against all remaining left indices.", "Use `<=` comparison so equal temperatures produce no pairs.", "The consumer extracts temperatures and sums the yielded pairs." ]
from collections.abc import Iterator def inversion_pairs(temps: list[float]) -> Iterator[tuple[int, int]]: """Yield each index pair (i, j) with i < j and temps[i] > temps[j].""" order: list[int] = list(range(len(temps))) def sort(lo: int, hi: int) -> Iterator[tuple[int, int]]: if hi - lo <= 1: ...
from solution import count_inversions, inversion_pairs def test_empty_log() -> None: assert count_inversions([]) == 0 def test_sorted_log() -> None: log = [("d1", 5.0), ("d2", 9.0), ("d3", 12.0)] assert count_inversions(log) == 0 def test_equal_temperatures_not_counted() -> None: assert count_inve...
from solution import count_inversions, inversion_pairs def test_count_inversions_empty_log_is_zero() -> None: assert count_inversions([]) == 0 def test_count_inversions_rising_log_is_zero() -> None: assert count_inversions([("d1", 1.0), ("d2", 2.0), ("d3", 3.0)]) == 0 def test_equal_temperatures_are_not_i...
ds-v4.1-flash
from typing import Iterator, List, Tuple def inversion_pairs(temps): order = list(range(len(temps))) def sort(lo, hi): if hi - lo <= 1: return mid = (lo + hi) // 2 for pair in sort(lo, mid): yield pair for pair in sort(mid, hi): yield pair ...
{ "mutant": "from collections.abc import Iterator\n\ndef inversion_pairs(temps: list[float]) -> Iterator[tuple[int, int]]:\n \"\"\"Yield each index pair (i, j) with i < j and temps[i] > temps[j].\"\"\"\n order: list[int] = list(range(len(temps)))\n\n def sort(lo: int, hi: int) -> Iterator[tuple[int, int]]:\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-f097892017612bbb
code
chainmap
ds
stateful_class
2
short
{ "kind": "legal", "text": "Payment procedures (the subject of 38 CFR 51.42, Pensions, Bonuses, and Veterans' Relief)", "sources": [ { "source": "ecfr", "id": "38 CFR 51.42", "agency": "DEPARTMENT OF VETERANS AFFAIRS" } ] }
glm-5.3-flash
For our benefits office I need layered payment settings: a base schedule of rates, plus override layers that staff can push and pop during a review. Write a class `PaymentLedger` with `__init__(self, base: dict[str, float])`, `push_layer(self, overrides: dict[str, float]) -> None`, `pop_layer(self) -> None`, `set_overr...
[ "Store layers as a list of dicts, base first.", "`push_layer` appends a copy; `pop_layer` refuses to remove the base.", "`set_override` writes into the top layer.", "`summary` builds a `ChainMap` over the layers in reverse so the top wins." ]
from collections import ChainMap class PaymentLedger: """Layered payment settings where higher layers shadow lower ones.""" def __init__(self, base: dict[str, float]) -> None: """Start with a single base layer copied from base.""" self._layers: list[dict[str, float]] = [dict(base)] def p...
from solution import PaymentLedger def test_higher_layer_shadows() -> None: ledger = PaymentLedger({"monthly_rate": 900.0, "copay": 15.0}) ledger.push_layer({"monthly_rate": 1200.0}) assert ledger.summary() == {"monthly_rate": 1200.0, "copay": 15.0} def test_pop_restores_values() -> None: ledger = P...
from solution import PaymentLedger def test_summary_shadows_lower_layers() -> None: ledger = PaymentLedger({"a": 1.0, "b": 2.0}) ledger.push_layer({"a": 5.0, "c": 3.0}) assert ledger.summary() == {"a": 5.0, "b": 2.0, "c": 3.0} def test_push_then_pop_restores_earlier_values() -> None: ledger = Paymen...
ds-v4.1-flash
from collections import ChainMap class PaymentLedger(object): def __init__(self, base): self._layers = [dict(base)] def push_layer(self, overrides): self._layers.append(dict(overrides)) def pop_layer(self): if len(self._layers) == 1: raise IndexError("the base layer c...
{ "mutant": "from collections import ChainMap\n\nclass PaymentLedger:\n \"\"\"Layered payment settings where higher layers shadow lower ones.\"\"\"\n\n def __init__(self, base: dict[str, float]) -> None:\n \"\"\"Start with a single base layer copied from base.\"\"\"\n self._layers: list[dict[str, ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-2dd9510c4c8d3e53
code
graphlib
py
function
5
short
{ "kind": "og", "text": "amniote (A vertebrate whose embryo develops within an egg containing protective extraembryonic membranes, enabling reproduction on dry land)", "sources": [ { "source": "opengloss", "id": "og-glossary:amniote", "headword": "amniote" } ] }
glm-5.3-flash
I'm modelling the developmental programme of an amniote embryo as a task graph and need a fixed processing order. Write one top-level function `stage_order(tasks: dict[str, set[str]]) -> list[str]` (small helpers allowed) that maps each stage name to its set of prerequisite stage names and returns an order in which eve...
[ "Validate that every prerequisite is a known stage, else raise `KeyError`.", "Build a `TopologicalSorter` from a copied graph and call `prepare()`.", "While stages remain, take the ready batch and extend the result with it sorted.", "Mark each emitted stage done and return the accumulated order." ]
from graphlib import TopologicalSorter def stage_order(tasks: dict[str, set[str]]) -> list[str]: """Order development stages so each stage follows its prerequisites.""" for prereqs in tasks.values(): for pre in prereqs: if pre not in tasks: raise KeyError(pre) sorter = ...
from graphlib import CycleError from solution import stage_order def test_empty_graph() -> None: assert stage_order({}) == [] def test_valid_order_respects_prerequisites() -> None: tasks = {"hatch": {"grow"}, "grow": {"cleavage"}, "cleavage": set()} order = stage_order(tasks) assert order.index("cl...
from graphlib import CycleError from solution import stage_order def test_empty_tasks_returns_empty_list() -> None: assert stage_order({}) == [] def test_stages_without_prerequisites_start_alphabetically() -> None: assert stage_order({"c": set(), "a": set(), "b": set()}) == ["a", "b", "c"] def test_each_...
ds-v4.1-flash
from graphlib import CycleError, TopologicalSorter def stage_order(tasks): for stage in tasks.keys(): for pre in tasks[stage]: if pre not in tasks.keys(): raise KeyError(pre) graph = {} for stage in tasks.keys(): graph[stage] = set(tasks[stage]) sorter = Top...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-9975bb53e043e323
code
flatten
alg
enum_plus_fn
2
short
{ "kind": "og", "text": "slipper (A soft, comfortable indoor shoe worn inside buildings, typically with a flat sole and minimal structure, and often backless or open-backed)", "sources": [ { "source": "opengloss", "id": "og-glossary:slipper", "headword": "slipper" } ] }
ds-v4.1-flash
Our workshop keeps slipper part lists as deeply nested lists of strings, and the display desk needs one flat list per style. Please write `SlipperStyle`, an Enum with the members MULE, CLOG, SCUFF and DISPLAY_ONLY, together with `slipper_parts(style: SlipperStyle, bundles: dict[SlipperStyle, Bundle], *, drop: str | Non...
[ "Declare the recursive `Bundle` type alias and the `SlipperStyle` enum.", "Write a private recursive generator that yields strings and recurses into lists.", "Dispatch on the enum: DISPLAY_ONLY short-circuits, other styles index `bundles`.", "Filter the flattened labels by `drop` unless it is None." ]
from collections.abc import Iterator from enum import Enum, auto type Bundle = str | list[Bundle] class SlipperStyle(Enum): """Indoor slipper styles handled by the parts desk.""" MULE = auto() CLOG = auto() SCUFF = auto() DISPLAY_ONLY = auto() def _labels(bundle: Bundle) -> Iterator[str]: ...
from solution import SlipperStyle, slipper_parts def test_display_only_returns_empty_without_reading_the_mapping() -> None: assert slipper_parts(SlipperStyle.DISPLAY_ONLY, {}) == [] def test_labels_are_flattened_depth_first() -> None: bundles = {SlipperStyle.MULE: ["sole", ["upper", ["strap"]], "tag"]} ...
from solution import Bundle, SlipperStyle, slipper_parts def test_display_only_ignores_bundles() -> None: assert slipper_parts(SlipperStyle.DISPLAY_ONLY, {}, drop="sole") == [] assert slipper_parts(SlipperStyle.DISPLAY_ONLY, {}) == [] def test_missing_style_raises() -> None: try: slipper_parts(S...
glm-5.3-flash
from typing import Dict, Iterator, List, Optional, Union Bundle = Union[str, List["Bundle"]] class SlipperStyle: MULE = "MULE" CLOG = "CLOG" SCUFF = "SCUFF" DISPLAY_ONLY = "DISPLAY_ONLY" def _labels(bundle: Bundle) -> Iterator[str]: if isinstance(bundle, str): yield bundle retur...
{ "mutant": "from collections.abc import Iterator\nfrom enum import Enum, auto\ntype Bundle = str | list[Bundle]\n\nclass SlipperStyle(Enum):\n \"\"\"Indoor slipper styles handled by the parts desk.\"\"\"\n MULE = auto()\n CLOG = auto()\n SCUFF = auto()\n DISPLAY_ONLY = auto()\n\ndef _labels(bundle: Bu...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-fb861da2fbd538e5
code
bitset
ds
function
4
short
{ "kind": "topic", "text": "daughter cell (a topic in nature)", "sources": [ { "source": "opengloss", "id": "og-enc:daughter cell", "headword": "daughter cell" } ] }
ds-v4.1-flash
A daughter cell in our cultures is described by two chromosome marker masks packed into single ints, one from the host chromatid and one from the donor. Write `daughter_cell(host: int, donor: int, *, forced: int = 0) -> tuple[int, int, int]`; it returns the retained mask, the dropped mask and the number of retained mar...
[ "Reject negative masks with ValueError.", "Compute shared bits with `host & donor` and OR in the forced bits.", "Compute the unambiguous bits with `host ^ donor`, then clear the forced bits.", "Return the two masks plus the retained popcount." ]
def daughter_cell(host: int, donor: int, *, forced: int = 0) -> tuple[int, int, int]: """Return the retained mask, the dropped mask and the retained marker count.""" if host < 0 or donor < 0 or forced < 0: raise ValueError("marker masks must not be negative") retained = (host & donor) | forced d...
from solution import daughter_cell def test_shared_markers_are_retained_and_single_markers_dropped() -> None: retained, dropped, count = daughter_cell(0b1011, 0b1001) assert retained == 0b1001 assert dropped == 0b0010 assert count == 2 def test_identical_masks_drop_nothing() -> None: retained, d...
from solution import daughter_cell def test_retained_is_intersection() -> None: assert daughter_cell(0b1100, 0b1010) == (0b1000, 0b0110, 1) def test_dropped_is_exclusive_or() -> None: assert daughter_cell(0b1100, 0b1010)[1] == 0b0110 def test_identical_masks_have_no_drops() -> None: retained, dropped,...
glm-5.3-flash
from typing import Tuple def daughter_cell(host: int, donor: int, *, forced: int = 0) -> Tuple[int, int, int]: if host < 0 or donor < 0 or forced < 0: raise ValueError("marker masks must not be negative") retained = (host & donor) | forced dropped = (host ^ donor) & ~forced count = 0 for d...
{ "mutant": "def daughter_cell(host: int, donor: int, *, forced: int=1) -> tuple[int, int, int]:\n \"\"\"Return the retained mask, the dropped mask and the retained marker count.\"\"\"\n if host < 0 or donor < 0 or forced < 0:\n raise ValueError('marker masks must not be negative')\n retained = host &...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-ed029dc01e4cb2b2
code
heap_merge
ds
pure_pipeline
4
short
{ "kind": "og", "text": "monoplane (An aircraft with a single main wing plane, as opposed to multiple stacked wings such as in a biplane or triplane)", "sources": [ { "source": "opengloss", "id": "og-glossary:monoplane", "headword": "monoplane" } ] }
ds-v4.1-flash
A test-flight team logs climb samples from three independent altimeters on a monoplane, and each altimeter writes its samples already in ascending order. I want three small functions plus one pipeline. Give me `merge_climbs(streams: list[list[int]]) -> list[int]`, which takes the per-altimeter sample lists and returns ...
[ "`merge_climbs` checks each stream with `pairwise` and raises `ValueError` on a decrease, then returns `list(heapq.merge(*streams))`.", "`collapse_duplicates` keeps a value when it is the first item or differs from the previous one.", "`climb_profile` composes merge, collapse and a `minimum` filter into one ord...
"""Merge already-sorted monoplane climb samples.""" from heapq import merge from itertools import pairwise def merge_climbs(streams: list[list[int]]) -> list[int]: """Merge sorted climb-sample streams into one non-decreasing list.""" for stream in streams: if any(later < earlier for earlier, later in...
from solution import climb_profile, collapse_duplicates, merge_climbs def test_merge_orders_two_streams() -> None: assert merge_climbs([[120, 400], [100, 300]]) == [100, 120, 300, 400] def test_merge_of_three_streams_is_non_decreasing() -> None: merged = merge_climbs([[100, 900], [100, 400, 400], [250]]) ...
from solution import climb_profile, collapse_duplicates, merge_climbs def test_merge_climbs_merges_sorted_streams() -> None: assert merge_climbs([[1, 3, 5], [2, 3, 6]]) == [1, 2, 3, 3, 5, 6] def test_merge_climbs_empty_streams() -> None: assert merge_climbs([]) == [] assert merge_climbs([[], []]) == [] ...
glm-5.3-flash
"""Merge already-sorted monoplane climb samples.""" from heapq import merge from typing import List def merge_climbs(streams: List[List[int]]) -> List[int]: """Merge sorted climb-sample streams into one non-decreasing list.""" for stream in streams: for index in range(1, len(stream)): if ...
{ "mutant": "\"\"\"Merge already-sorted monoplane climb samples.\"\"\"\nfrom heapq import merge\nfrom itertools import pairwise\n\ndef merge_climbs(streams: list[list[int]]) -> list[int]:\n \"\"\"Merge sorted climb-sample streams into one non-decreasing list.\"\"\"\n for stream in streams:\n if any((late...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, ...
ol5-ea40330aa0ea6560
code
counter
ds
generator
4
short
{ "kind": "legal", "text": "Increase in construction charges (the subject of 43 U.S.C. 469, Public Lands)", "sources": [ { "source": "usc", "id": "43 U.S.C. 469" } ] }
ds-v4.1-flash
A county office tracks increases in construction charges on public-land parcels, and the review sheet lists `(parcel, old_charge, new_charge)` triples in the order they were filed. Write `iter_increases(records: Iterable[tuple[str, int, int]]) -> Iterator[ChargeIncrease]` as a generator that yields one `ChargeIncrease`...
[ "`iter_increases` unpacks each triple and yields a `ChargeIncrease` only when the new charge is strictly higher.", "`top_increase_parcels` rejects a `limit` below 1 with `ValueError`.", "It tallies the yielded parcels with `Counter`, takes `most_common`, re-sorts for the tie rule and slices to `limit`." ]
"""Tally construction-charge increases on public-land parcels.""" from collections import Counter from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass(slots=True, frozen=True) class ChargeIncrease: """One parcel whose construction charge went up.""" parcel: str amo...
from solution import iter_increases, top_increase_parcels def test_iter_increases_skips_non_increases() -> None: records = [("P-1", 400, 900), ("P-2", 700, 700), ("P-2", 950, 900), ("P-1", 900, 1000)] found = [(item.parcel, item.amount) for item in iter_increases(records)] assert found == [("P-1", 500), (...
from solution import ChargeIncrease, iter_increases, top_increase_parcels def test_increase_yields_difference() -> None: result = list(iter_increases([("p1", 100, 130)])) assert result == [ChargeIncrease(parcel="p1", amount=30)] def test_no_increase_yields_nothing() -> None: assert list(iter_increases([...
glm-5.3-flash
"""Tally construction-charge increases on public-land parcels.""" from collections import Counter from typing import Iterable, Iterator, List, NamedTuple, Tuple class ChargeIncrease(NamedTuple): """One parcel whose construction charge went up.""" parcel: str amount: int def iter_increases(records: Ite...
{ "mutant": "\"\"\"Tally construction-charge increases on public-land parcels.\"\"\"\nfrom collections import Counter\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\n\n@dataclass(slots=True, frozen=True)\nclass ChargeIncrease:\n \"\"\"One parcel whose construction charge went up...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-db0d639497ea5508
code
memoization
alg
function
2
short
{ "kind": "og", "text": "duff (The uppermost layer of forest floor made of partly decomposed leaves and other organic debris, affecting moisture retention and nutrient...)", "sources": [ { "source": "opengloss", "id": "og-glossary:duff", "headword": "duff" } ] }
ds-v4.1-flash
Rain percolating through the duff layer of a forest floor can pass down in steps of one, two or three units of depth. Write one top-level function `drip_paths(units: int) -> int` that counts the ordered step sequences whose sizes sum to exactly `units`. Rule 1: `drip_paths(0)` is 1, standing for the empty sequence, and...
[ "Wrap the recursive function in `functools.cache`.", "Reject negative depths before doing any work.", "Return 1 for depth 0.", "Sum the three shorter depths that remain non-negative." ]
"""Ordered percolation paths through a layer of duff.""" from functools import cache _STEPS = (1, 2, 3) @cache def drip_paths(units: int) -> int: """Count ordered 1, 2 and 3-unit steps that sum to exactly units.""" if units < 0: raise ValueError("units must not be negative") if units == 0: ...
from solution import drip_paths def test_zero_units_is_one_path() -> None: assert drip_paths(0) == 1 def test_small_counts() -> None: assert drip_paths(1) == 1 assert drip_paths(2) == 2 assert drip_paths(3) == 4 assert drip_paths(4) == 7 def test_negative_units_raise() -> None: try: ...
from solution import drip_paths def test_zero_units_is_one() -> None: assert drip_paths(0) == 1 def test_small_units_follow_recurrence() -> None: assert drip_paths(1) == 1 assert drip_paths(2) == 2 assert drip_paths(3) == 4 def test_larger_units_follow_recurrence() -> None: assert drip_paths(4...
glm-5.3-flash
null
{ "mutant": "\"\"\"Ordered percolation paths through a layer of duff.\"\"\"\nfrom functools import cache\n_STEPS = (1, 3, 3)\n\n@cache\ndef drip_paths(units: int) -> int:\n \"\"\"Count ordered 1, 2 and 3-unit steps that sum to exactly units.\"\"\"\n if units < 0:\n raise ValueError('units must not be neg...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [], "b...
ol5-c9ca7015ece130ca
code
star_unpacking
py
protocol_impl
1
short
{ "kind": "og", "text": "oeuvre (The complete works produced by a single artist or creator, regarded as a cohesive corpus)", "sources": [ { "source": "opengloss", "id": "og-glossary:oeuvre", "headword": "oeuvre" } ] }
ds-v4.1-flash
A gallery keeps coming back with loose lists of works, and we want one merged view of an artist's oeuvre. Define a `Catalogue` `Protocol` with a `title: str` attribute and a `works() -> list[str]` method, then two classes that satisfy it: `Solo`, a dataclass with `slots=True` holding a single `title` whose `works()` re...
[ "Split the arguments with `first, *rest = catalogues`.", "Choose the lead key from `leading` or the first catalogue's title and store its works if non-empty or `keep_empty`.", "Walk the remaining catalogues in order and store their works under the same emptiness test.", "Return the merged map." ]
"""Merging catalogues into one oeuvre.""" from dataclasses import dataclass from typing import Protocol class Catalogue(Protocol): """A named group of works with an ordered listing.""" title: str def works(self) -> list[str]: """Return the work titles in catalogue order.""" ... @datac...
from solution import Series, Solo, merge_oeuvre def test_first_catalogue_supplies_the_lead_key() -> None: merged = merge_oeuvre(Solo("Aurora"), Series("Tides", ["First", "Second"])) assert merged == {"Aurora": ["Aurora"], "Tides": ["First", "Second"]} def test_leading_keyword_replaces_the_lead_key() -> None...
from solution import Catalogue, Series, Solo, merge_oeuvre def test_solo_works() -> None: solo: Catalogue = Solo("Sketch") assert solo.works() == ["Sketch"] def test_series_works_returns_copy() -> None: members: list[str] = ["a", "b"] series: Catalogue = Series("Group", members) returned: list[s...
glm-5.3-flash
from typing import Dict, List, Protocol class Catalogue(Protocol): """A named group of works with an ordered listing.""" title: str def works(self) -> List[str]: ... class Solo: """A single work shown under its own title.""" def __init__(self, title: str) -> None: self.title =...
{ "mutant": "\"\"\"Merging catalogues into one oeuvre.\"\"\"\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nclass Catalogue(Protocol):\n \"\"\"A named group of works with an ordered listing.\"\"\"\n title: str\n\n def works(self) -> list[str]:\n \"\"\"Return the work titles in cata...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": true, "remaining": [], "b_remaining":...
ol5-4b0c04dfb9cdd4d9
code
generator
py
enum_plus_fn
5
short
{ "kind": "legal", "text": "Application (the subject of 7 CFR 15e.102, Agriculture)", "sources": [ { "source": "ecfr", "id": "7 CFR 15e.102" } ] }
ds-v4.1-flash
Write a generator function that yields application identifiers lazily. Define an enum `ApplicationKind` with three members: `FARM_LOAN`, `NUTRITION`, and `CONSERVATION`. Write a function `applications(kind: ApplicationKind, count: int) -> Iterator[str]` that yields exactly `count` identifiers for the given kind. Each i...
[ "Define `ApplicationKind` with string values.", "In `applications`, raise `ValueError` if `count` is negative.", "Dispatch on `kind` with `match` to choose the code.", "Loop from 1 to `count`, yielding formatted identifiers." ]
from collections.abc import Iterator from enum import Enum class ApplicationKind(Enum): """Kinds of applications accepted under the agriculture rule.""" FARM_LOAN = "farm-loan" NUTRITION = "nutrition" CONSERVATION = "conservation" def applications(kind: ApplicationKind, count: int) -> Iterator[str]...
from solution import ApplicationKind, applications def test_returns_generator() -> None: result = applications(ApplicationKind.FARM_LOAN, 3) assert iter(result) is result def test_negative_count_raises() -> None: gen = applications(ApplicationKind.NUTRITION, -1) try: next(gen) except Val...
from collections.abc import Generator from solution import ApplicationKind, applications def test_returns_generator() -> None: gen: Generator[str] = applications(ApplicationKind.NUTRITION, 3) # type: ignore[assignment] assert next(gen) == "APP-NU-0001" def test_negative_count_raises_on_next() -> None: ...
glm-5.3-flash
from typing import Iterator class ApplicationKind: """Kinds of applications accepted under the agriculture rule.""" FARM_LOAN = "farm-loan" NUTRITION = "nutrition" CONSERVATION = "conservation" def applications(kind: str, count: int) -> Iterator[str]: """Yield application identifiers for the gi...
{ "mutant": "from collections.abc import Iterator\nfrom enum import Enum\n\nclass ApplicationKind(Enum):\n \"\"\"Kinds of applications accepted under the agriculture rule.\"\"\"\n FARM_LOAN = 'farm-loan'\n NUTRITION = 'nutrition'\n CONSERVATION = 'conservation'\n\ndef applications(kind: ApplicationKind, c...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-38d8ddd130838d14
code
interval_scheduling_rooms
alg
dataclass_plus_fn
2
short
{ "kind": "og", "text": "twinjet (A fixed-wing aircraft powered by two jet engines, designed for efficiency, redundancy, and performance in regional and commercial operations)", "sources": [ { "source": "opengloss", "id": "og-glossary:twinjet", "headword": "twinjet" } ] }
ds-v4.1-flash
We keep losing track of hangar space at the twinjet base. Please write a module with a dataclass `Rotation(callsign: str, start_min: int, end_min: int)` and a function `min_bays(rotations: list[Rotation]) -> int` that returns the smallest number of hangar bays needed so that every rotation in the list has a bay for its...
[ "Define the `Rotation` dataclass with slots.", "Reject any rotation that does not end after it starts.", "Sort rotations by start minute.", "Keep a heap of end minutes; reuse the earliest free bay with `heapreplace`, otherwise push.", "Return the heap size, which is the peak concurrency." ]
"""Hangar planning for twinjet rotations.""" import heapq from dataclasses import dataclass @dataclass(slots=True) class Rotation: """One twinjet rotation occupying a hangar bay from start to end.""" callsign: str start_min: int end_min: int def min_bays(rotations: list[Rotation]) -> int: """R...
from solution import Rotation, min_bays def test_empty_schedule_needs_no_bays() -> None: assert min_bays([]) == 0 def test_touching_rotations_share_one_bay() -> None: rotations = [ Rotation("TJ101", 0, 60), Rotation("TJ202", 60, 120), Rotation("TJ303", 120, 180), ] assert min...
from solution import Rotation, min_bays def test_empty_list_needs_zero_bays() -> None: assert min_bays([]) == 0 def test_single_rotation_needs_one_bay() -> None: assert min_bays([Rotation("A1", 0, 60)]) == 1 def test_touching_rotations_share_a_bay() -> None: rotations = [Rotation("A1", 0, 30), Rotatio...
glm-5.3-flash
"""Hangar planning for twinjet rotations, older style.""" import heapq from typing import List class Rotation(object): """One twinjet rotation occupying a hangar bay from start to end.""" def __init__(self, callsign: str, start_min: int, end_min: int) -> None: self.callsign = callsign self.s...
{ "mutant": "\"\"\"Hangar planning for twinjet rotations.\"\"\"\nimport heapq\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Rotation:\n \"\"\"One twinjet rotation occupying a hangar bay from start to end.\"\"\"\n callsign: str\n start_min: int\n end_min: int\n\ndef min_bays(rotations...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-bf14af2ece87c553
code
comprehensions
py
protocol_impl
3
short
{ "kind": "legal", "text": "Use of fee-charging firms (the subject of 5 CFR 300.404, Administrative Personnel)", "sources": [ { "source": "ecfr", "id": "5 CFR 300.404", "agency": "OFFICE OF PERSONNEL MANAGEMENT" } ] }
ds-v4.1-flash
The fee-charging provisions behind 5 CFR 300.404 keep tripping up our billing tool, so I want a small model of firms that may charge a fee. Write a `Protocol` named `Firm` with a `name: str` attribute and a method `fee_for(self, amount_cents: int) -> int`, plus two classes that satisfy it: `FlatFeeFirm(name: str, fee_c...
[ "Define the `Firm` protocol with a name attribute and a `fee_for` method.", "Implement `FlatFeeFirm` and `ThresholdFirm` with their own fee calculation.", "Validate the amount once in each public function.", "Build the name list and the fee table with comprehensions that keep only positive fees." ]
"""A small model of firms that may charge a fee on an amount.""" from typing import Protocol class Firm(Protocol): """A firm that may charge a fee for a given amount.""" name: str def fee_for(self, amount_cents: int) -> int: """Return the fee this firm charges on the amount, in cents.""" ...
from solution import FlatFeeFirm, ThresholdFirm, charging_names, fee_table def test_charging_names_keeps_order_and_drops_zero_fees() -> None: firms = [ FlatFeeFirm("Ardent", 250), ThresholdFirm("Blythe", 5000, 400), FlatFeeFirm("Corvid", 0), ] assert charging_names(firms, 1000) == ...
from solution import Firm, FlatFeeFirm, ThresholdFirm, charging_names, fee_table def make_firms() -> list[Firm]: flat: Firm = FlatFeeFirm("flatco", 500) low: Firm = ThresholdFirm("lowth", 100, 200) high: Firm = ThresholdFirm("highth", 1_000, 900) return [flat, low, high] def test_flat_firm_charges_o...
glm-5.3-flash
"""A small model of firms that may charge a fee, older style.""" from typing import Dict, List, Protocol class Firm(Protocol): """A firm that may charge a fee for a given amount.""" name: str def fee_for(self, amount_cents: int) -> int: """Return the fee this firm charges on the amount, in cent...
{ "mutant": "\"\"\"A small model of firms that may charge a fee on an amount.\"\"\"\nfrom typing import Protocol\n\nclass Firm(Protocol):\n \"\"\"A firm that may charge a fee for a given amount.\"\"\"\n name: str\n\n def fee_for(self, amount_cents: int) -> int:\n \"\"\"Return the fee this firm charges...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_...
ol5-4b8b354fdeed1c29
code
diffing_text
alg
generator
5
short
{ "kind": "topic", "text": "jacinth (a topic in nature)", "sources": [ { "source": "opengloss", "id": "og-enc:jacinth", "headword": "jacinth" } ] }
ds-v4.1-flash
I have two short field notes about jacinth plants, and I want a line-level diff rather than a character-level one. Write `iter_jacinth_diff(before: str, after: str) -> Iterator[tuple[str, str]]`, a generator that yields `(marker, line)` pairs for line-level changes. Also write `diff_tally(before: str, after: str) -> di...
[ "Split both texts into line lists with `splitlines`.", "Build a `SequenceMatcher` over those lists.", "Walk its opcodes and yield equal, delete, insert, and replace lines in order.", "Tally markers from the generator in `diff_tally`." ]
import difflib from collections.abc import Iterator def iter_jacinth_diff(before: str, after: str) -> Iterator[tuple[str, str]]: """Yield marker and line pairs for a line-level jacinth note diff.""" old = before.splitlines() new = after.splitlines() matcher = difflib.SequenceMatcher(a=old, b=new, auto...
from solution import diff_tally, iter_jacinth_diff def test_equal_lines_use_space_marker() -> None: assert list(iter_jacinth_diff("a\nb\n", "a\nb\n")) == [(" ", "a"), (" ", "b")] def test_delete_and_insert_markers() -> None: assert list(iter_jacinth_diff("a\nb", "a\nc")) == [(" ", "a"), ("-", "b"), ("+", "c...
from solution import diff_tally, iter_jacinth_diff def test_identical_texts_give_same_lines() -> None: pairs = list(iter_jacinth_diff("a\nb", "a\nb")) assert pairs == [(" ", "a"), (" ", "b")] def test_pure_insertion_and_deletion() -> None: assert list(iter_jacinth_diff("", "x")) == [("+", "x")] asse...
glm-5.3-flash
import difflib from typing import Dict, Iterator, Tuple def iter_jacinth_diff(before: str, after: str) -> Iterator[Tuple[str, str]]: """Yield marker and line pairs for a line-level jacinth note diff.""" old = before.splitlines() new = after.splitlines() matcher = difflib.SequenceMatcher(None, old, new...
{ "mutant": "import difflib\nfrom collections.abc import Iterator\n\ndef iter_jacinth_diff(before: str, after: str) -> Iterator[tuple[str, str]]:\n \"\"\"Yield marker and line pairs for a line-level jacinth note diff.\"\"\"\n old = before.splitlines()\n new = after.splitlines()\n matcher = difflib.Sequenc...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b...
ol5-301c8e8030fccfae
code
primes_sieve
alg
function
2
short
{ "kind": "legal", "text": "Franchise application process (the subject of 47 CFR 76.41, Telecommunication)", "sources": [ { "source": "ecfr", "id": "47 CFR 76.41", "agency": "FEDERAL COMMUNICATIONS COMMISSION" } ] }
ds-v4.1-flash
For a franchise application process, I mark application numbers that get expedited review when the number itself is prime. Write one top-level function `expedited_ids(limit: int) -> list[int]` using a sieve of Eratosthenes. Rule 1: if `limit` is less than 2, raise `ValueError`. Rule 2: otherwise return the prime applic...
[ "Reject limits below 2.", "Build a boolean sieve up to the limit.", "Mark multiples of each prime starting at its square.", "Collect and return the remaining prime numbers in order." ]
def expedited_ids(limit: int) -> list[int]: """Return prime application numbers from 2 through limit.""" if limit < 2: raise ValueError("limit must be at least 2") flags = [True] * (limit + 1) flags[0] = False flags[1] = False factor = 2 while factor * factor <= limit: if fla...
from solution import expedited_ids def test_small_limit() -> None: assert expedited_ids(10) == [2, 3, 5, 7] def test_two() -> None: assert expedited_ids(2) == [2] def test_below_two_raises() -> None: try: expedited_ids(1) except ValueError: pass else: raise AssertionErr...
from solution import expedited_ids def test_limit_below_two_raises() -> None: for limit in (-5, 0, 1): try: expedited_ids(limit) except ValueError: pass else: raise AssertionError def test_smallest_limit() -> None: assert expedited_ids(2) == [2] ...
glm-5.3-flash
from typing import List def expedited_ids(limit: int) -> List[int]: """Return prime application numbers from 2 through limit.""" if limit < 2: raise ValueError("limit must be at least 2") flags = [True] * (limit + 1) flags[0] = False flags[1] = False factor = 2 while factor * facto...
{ "mutant": "def expedited_ids(limit: int) -> list[int]:\n \"\"\"Return prime application numbers from 2 through limit.\"\"\"\n if limit < 2:\n raise ValueError('limit must be at least 2')\n flags = [True] // (limit + 1)\n flags[0] = False\n flags[1] = False\n factor = 2\n while factor * f...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [], "b...
ol5-3eb82aaa0ae989dc
code
iterator_protocol
py
class
2
short
{ "kind": "topic", "text": "stolichnaya (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:stolichnaya", "headword": "stolichnaya" } ] }
ds-v4.1-flash
A colleague needs a small helper for the bar at the back of the kitchen: a bottle of spirit that is served in measured pours. Write a class `Bottle` with `Bottle(volume_ml: int, *, pour_ml: int = 50)`, `__iter__` and `__next__`. Constructing it with a non-positive volume or pour raises `ValueError`. Rule 1: `iter(bottl...
[ "Store the remaining volume and the pour size, rejecting non-positive values.", "`__iter__` returns the bottle itself.", "`__next__` raises `StopIteration` when nothing is left.", "Otherwise take the smaller of the pour size and the remainder, subtract it, and return it." ]
"""Serve a bottle of spirit in fixed pours with the iterator protocol.""" class Bottle: """Iterate the pours of a bottle measured in millilitres.""" __slots__ = ("_pour_ml", "_remaining") def __init__(self, volume_ml: int, *, pour_ml: int = 50) -> None: """Store the volume and the standard pour ...
from solution import Bottle def test_pours_sum_to_volume() -> None: bottle = Bottle(220) assert list(bottle) == [50, 50, 50, 50, 20] def test_iter_returns_the_same_object() -> None: bottle = Bottle(100) assert iter(bottle) is bottle def test_exact_multiple_has_no_zero_pour() -> None: assert li...
from solution import Bottle def test_invalid_construction_raises() -> None: for volume, pour in ((0, 50), (-10, 50), (100, 0), (100, -5)): try: Bottle(volume, pour_ml=pour) except ValueError: pass else: raise AssertionError def test_iter_returns_self()...
glm-5.3-flash
"""Serve a bottle of spirit in fixed pours with the iterator protocol.""" class Bottle(object): """Iterate the pours of a bottle measured in millilitres.""" def __init__(self, volume_ml, pour_ml=50): """Store the volume and the standard pour size, rejecting non-positive values.""" if volume_m...
{ "mutant": "\"\"\"Serve a bottle of spirit in fixed pours with the iterator protocol.\"\"\"\n\nclass Bottle:\n \"\"\"Iterate the pours of a bottle measured in millilitres.\"\"\"\n __slots__ = ('_pour_ml', '_remaining')\n\n def __init__(self, volume_ml: int, *, pour_ml: int=50) -> None:\n \"\"\"Store ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-bcb5c604f549f8c7
code
protocol
py
enum_plus_fn
3
short
{ "kind": "legal", "text": "Transfer of amounts appropriated for Architect of the Capitol under House Office Buildings (the subject of 2 U.S.C. 1862b, The Congress)", "sources": [ { "source": "usc", "id": "2 U.S.C. 1862b" } ] }
ds-v4.1-flash
Help the finance office move money between the accounts that hold the appropriation for House Office Buildings. There is an enum `TransferKind` with the members `HOUSE_OFFICE_BUILDINGS`, `CAPITOL_GROUNDS` and `RESERVE`, a `Protocol` named `Ledger` with the methods `balance(account: str) -> int`, `debit(account: str, am...
[ "Reject a non-positive amount before touching the ledger.", "Look up the fixed source account for the enum member.", "Reject a destination equal to the source.", "Debit the source, credit the destination, and return the destination balance." ]
"""Move appropriated amounts between Architect of the Capitol accounts.""" from enum import Enum from typing import Protocol, runtime_checkable class TransferKind(Enum): """The appropriation line that funds a transfer.""" HOUSE_OFFICE_BUILDINGS = "house_office_buildings" CAPITOL_GROUNDS = "capitol_groun...
from solution import Ledger, TransferKind, transfer class FakeLedger: def __init__(self, balances: dict[str, int]) -> None: self.balances = balances self.calls: list[tuple[str, str, int]] = [] def balance(self, account: str, /) -> int: return self.balances[account] def debit(self...
from solution import TransferKind, transfer class FakeLedger: def __init__(self, balances: dict[str, int]) -> None: self.balances = dict(balances) def balance(self, account: str, /) -> int: return self.balances[account] def debit(self, account: str, amount: int, /) -> None: self....
glm-5.3-flash
null
{ "mutant": "\"\"\"Move appropriated amounts between Architect of the Capitol accounts.\"\"\"\nfrom enum import Enum\nfrom typing import Protocol, runtime_checkable\n\nclass TransferKind(Enum):\n \"\"\"The appropriation line that funds a transfer.\"\"\"\n HOUSE_OFFICE_BUILDINGS = 'house_office_buildings'\n C...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": []...
ol5-c4559a1b27c50e18
code
queue_fifo
ds
enum_plus_fn
1
short
{ "kind": "topic", "text": "energy availability (a topic in science)", "sources": [ { "source": "opengloss", "id": "og-enc:energy availability", "headword": "energy availability" } ] }
glm-5.3-flash
Our grid team tracks how much offered energy actually gets absorbed, and the offers have to be served strictly in the order they arrived. Write an `Enum` `Source` with members `SOLAR`, `WIND` and `GRID`, a dispatcher `efficiency(source: Source) -> float` returning 0.75, 0.5 and 1.0 respectively, a slots dataclass `Offe...
[ "Define the `Source` enum and dispatch on it with a `match` statement.", "Define the `Offer` dataclass.", "In `absorb`, pop from the left of the deque until empty, accumulating absorbed power.", "On a negative offer at the front, raise `ValueError` (the offending offer is already popped)." ]
"""FIFO dispatch of offered power into an availability ledger.""" import enum from collections import deque from dataclasses import dataclass class Source(enum.Enum): """Kinds of generation offering energy.""" SOLAR = "solar" WIND = "wind" GRID = "grid" def efficiency(source: Source) -> float: ...
from collections import deque from solution import Offer, Source, absorb def test_fifo_order_and_dispatch() -> None: offers = deque([Offer(Source.SOLAR, 100.0), Offer(Source.GRID, 100.0)]) assert absorb(offers) == 175.0 def test_wind_efficiency() -> None: assert absorb(deque([Offer(Source.WIND, 10.0)])...
from collections import deque from solution import Offer, Source, absorb, efficiency def test_efficiency_values() -> None: assert efficiency(Source.SOLAR) == 0.75 assert efficiency(Source.WIND) == 0.5 assert efficiency(Source.GRID) == 1.0 def test_absorb_sums_fifo_weighted_offers() -> None: offers:...
ds-v4.1-flash
null
{ "mutant": "\"\"\"FIFO dispatch of offered power into an availability ledger.\"\"\"\nimport enum\nfrom collections import deque\nfrom dataclasses import dataclass\n\nclass Source(enum.Enum):\n \"\"\"Kinds of generation offering energy.\"\"\"\n SOLAR = 'solar'\n WIND = 'wind'\n GRID = 'grid'\n\ndef effici...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": []...
ol5-e1ef51913a5490ab
code
intenum_flags
py
parser_plus_model
3
short
{ "kind": "topic", "text": "alces (a topic in science)", "sources": [ { "source": "opengloss", "id": "og-enc:alces", "headword": "alces" } ] }
glm-5.3-flash
Our field team logs moose (Alces alces) sightings as comma-separated tag strings, and I want them turned into structured records. Write an `enum.Flag` `MooseFeature` with members `NONE`, `ANTLERS`, `CALF`, `COLLAR`, `TRACKS`, a slots dataclass `Sighting(site: str, features: MooseFeature)` with a method `has(self, featu...
[ "Define the flag enum with `NONE` as 0 and the rest as `auto()`.", "Build a lowercase name-to-member lookup dict.", "Split the tag text, normalise each token, skip empties, and raise `ValueError` on unknown names.", "OR the recognised members together and build the `Sighting`.", "`has` uses flag membership ...
"""Parsing moose (Alces alces) sighting tags into feature flags.""" import enum from dataclasses import dataclass class MooseFeature(enum.Flag): """Observable features recorded at a moose sighting.""" NONE = 0 ANTLERS = enum.auto() CALF = enum.auto() COLLAR = enum.auto() TRACKS = enum.auto()...
from solution import MooseFeature, parse_sighting def test_parse_combines_tags() -> None: sighting = parse_sighting("ridge", "antlers, calf") assert sighting.features == MooseFeature.ANTLERS | MooseFeature.CALF assert sighting.site == "ridge" def test_unknown_tag_raises() -> None: try: parse...
from solution import MooseFeature, Sighting, parse_sighting def test_known_tags_are_combined() -> None: sighting = parse_sighting("Lakeshore", "antlers, collar") assert sighting.site == "Lakeshore" assert sighting.features == MooseFeature.ANTLERS | MooseFeature.COLLAR def test_tags_are_stripped_and_lowe...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Parsing moose (Alces alces) sighting tags into feature flags.\"\"\"\nimport enum\nfrom dataclasses import dataclass\n\nclass MooseFeature(enum.Flag):\n \"\"\"Observable features recorded at a moose sighting.\"\"\"\n NONE = 1\n ANTLERS = enum.auto()\n CALF = enum.auto()\n COLLAR = enu...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": true, "btests_changed": false, "remaining": [], "b_r...
ol5-08420f0e4e08554e
code
tree_recursive
ds
enum_plus_fn
1
short
{ "kind": "og", "text": "alkalies (A soluble base that forms hydroxide ions in aqueous solution and neutralizes acids)", "sources": [ { "source": "opengloss", "id": "og-glossary:alkalies", "headword": "alkalies" } ] }
glm-5.3-flash
Write a module about dosing alkali solutions. Define an enum `Alkali` with members `SODA_LYE`, `CAUSTIC_POTASH` and `LIME_WATER`, where each member carries a display name and the number of hydroxide ions one formula unit releases. Define frozen dataclass `Dose(alkali: Alkali, moles: float)` and dataclass `Blend(parts: ...
[ "Store the ion count inside each `Alkali` member as its enum value.", "`ions_per_unit` matches on the enum members and returns the ion count.", "`hydroxide_moles` pattern-matches the node type: a `Dose` multiplies moles by ions, a `Blend` recurses over its parts.", "An empty blend is rejected with `ValueError...
from dataclasses import dataclass from enum import Enum, unique @unique class Alkali(Enum): """Alkalis with the hydroxide ions one formula unit releases in water.""" SODA_LYE = ("sodium hydroxide", 1) CAUSTIC_POTASH = ("potassium hydroxide", 1) LIME_WATER = ("calcium hydroxide", 2) @dataclass(slots...
from solution import Alkali, Blend, Dose, hydroxide_moles, ions_per_unit def test_pure_dose() -> None: assert hydroxide_moles(Dose(Alkali.LIME_WATER, 0.5)) == 1.0 def test_nested_blend() -> None: inner = Blend([Dose(Alkali.SODA_LYE, 2.0)]) outer = Blend([inner, Dose(Alkali.CAUSTIC_POTASH, 3.0)]) ass...
from solution import Alkali, Blend, Dose, hydroxide_moles, ions_per_unit def test_ions_per_unit() -> None: assert ions_per_unit(Alkali.SODA_LYE) == 1 assert ions_per_unit(Alkali.CAUSTIC_POTASH) == 1 assert ions_per_unit(Alkali.LIME_WATER) == 2 def test_enum_carries_name_and_count() -> None: assert A...
ds-v4.1-flash
from typing import List, Union class Alkali(object): """Alkali kinds as plain class attributes.""" def __init__(self, label, ions): self.label = label self.ions = ions Alkali.SODA_LYE = Alkali("sodium hydroxide", 1) Alkali.CAUSTIC_POTASH = Alkali("potassium hydroxide", 1) Alkali.LIME_WATER ...
{ "mutant": "from dataclasses import dataclass\nfrom enum import Enum, unique\n\n@unique\nclass Alkali(Enum):\n \"\"\"Alkalis with the hydroxide ions one formula unit releases in water.\"\"\"\n SODA_LYE = ('sodium hydroxide', 1)\n CAUSTIC_POTASH = ('potassium hydroxide', 1)\n LIME_WATER = ('calcium hydrox...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-c61ce667e6bbc470
code
regex
py
module
4
short
{ "kind": "og", "text": "loess (A wind-blown silt deposit formed by aeolian processes, typically comprising silt-sized particles that accumulate to form extensive belts)", "sources": [ { "source": "opengloss", "id": "og-glossary:loess", "headword": "loess" } ] }
glm-5.3-flash
Our loess survey lab records each core sample as one compact log line. Write a module with two functions. `parse_sample(line: str) -> SampleRecord` takes a line like `"core K-114 | depth 2.75m | silt 84.2% | quartz 61.0%"` and returns a `SampleRecord` dataclass with fields `core: str`, `depth: float`, `silt: float`, `q...
[ "Define a frozen, slotted `SampleRecord` dataclass.", "Compile a regex with named groups for core, depth, silt, quartz; anchor the whole line.", "`parse_sample` matches the line, raises `ValueError` on a failed match or negative depth, and builds the record.", "`silt_band` compares `silt` against the two thre...
"""Parsing of loess core-sample log lines.""" import re from dataclasses import dataclass @dataclass(frozen=True, slots=True) class SampleRecord: """One parsed loess core sample.""" core: str depth: float silt: float quartz: float _LINE_RE = re.compile( r"core (?P<core>[A-Za-z0-9-]+) \| de...
from solution import SampleRecord, parse_sample, silt_band def test_parses_typical_line() -> None: rec = parse_sample("core K-114 | depth 2.75m | silt 84.2% | quartz 61.0%") assert rec == SampleRecord(core="K-114", depth=2.75, silt=84.2, quartz=61.0) def test_preserves_core_casing() -> None: assert pars...
from solution import SampleRecord, parse_sample, silt_band def test_parse_full_line() -> None: record = parse_sample("core K-114 | depth 2.75m | silt 84.2% | quartz 61.0%") assert record == SampleRecord(core="K-114", depth=2.75, silt=84.2, quartz=61.0) def test_parse_percent_with_space_before_sign() -> None...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Parsing of loess core-sample log lines.\"\"\"\nimport re\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass SampleRecord:\n \"\"\"One parsed loess core sample.\"\"\"\n core: str\n depth: float\n silt: float\n quartz: float\n_LINE_RE = re.compile('core (?...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-c3691419eb570da0
code
boundary_values
test
parser_plus_model
3
short
{ "kind": "legal", "text": "Eligibility and procedure for registration of an apprenticeship program (the subject of 29 CFR 29.3, Labor)", "sources": [ { "source": "ecfr", "id": "29 CFR 29.3" } ] }
glm-5.3-flash
State labor offices register apprenticeship programs, and applicants keep getting the age and hour bounds wrong, so we need a strict intake checker. Write `ApprenticeshipRule` as a dataclass with fields `min_age: int`, `max_age: int`, `min_hours: int` and `max_hours: int`. Write `validate_rule(min_age: int, max_age: in...
[ "Define the slotted dataclass holding the four bounds.", "Check each lower bound against its inclusive minimum, raising `ValueError` for the just-below value.", "Check each upper bound against its inclusive maximum, raising `ValueError` for the just-above value.", "Check the two cross-ordering conditions and ...
"""Intake checks for apprenticeship program registration.""" from dataclasses import dataclass MIN_AGE_LIMIT = 16 MAX_AGE_LIMIT = 65 MIN_HOURS_LIMIT = 2000 MAX_HOURS_LIMIT = 10000 @dataclass(slots=True) class ApprenticeshipRule: """Age and hour bounds of one registered program.""" min_age: int max_age:...
from solution import ApprenticeshipRule, validate_rule def test_inclusive_minima_accepted() -> None: rule = validate_rule(16, 65, 2000, 10000) assert rule == ApprenticeshipRule(16, 65, 2000, 10000) def test_age_just_below_raises() -> None: try: validate_rule(15, 40, 2000, 8000) except ValueE...
from solution import ApprenticeshipRule, validate_rule def test_valid_rule_returns_dataclass() -> None: rule = validate_rule(16, 65, 2000, 10000) assert rule == ApprenticeshipRule(min_age=16, max_age=65, min_hours=2000, max_hours=10000) def test_min_age_below_limit_raises() -> None: try: validat...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Intake checks for apprenticeship program registration.\"\"\"\nfrom dataclasses import dataclass\nMIN_AGE_LIMIT = 16\nMAX_AGE_LIMIT = 66\nMIN_HOURS_LIMIT = 2000\nMAX_HOURS_LIMIT = 10000\n\n@dataclass(slots=True)\nclass ApprenticeshipRule:\n \"\"\"Age and hour bounds of one registered program.\"\"...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [...
ol5-92d4d822b6ed57cc
code
dedupe_order
alg
protocol_impl
6
short
{ "kind": "legal", "text": "Application requirements (the subject of 47 CFR 2.911, Telecommunication)", "sources": [ { "source": "ecfr", "id": "47 CFR 2.911", "agency": "FEDERAL COMMUNICATIONS COMMISSION" } ] }
glm-5.3-flash
Our telecom filing desk merges the section lists of different application kinds. Write a `Protocol` named `RequirementsSource` with one method `required_sections(self) -> list[str]`, two classes that satisfy it, and `merged_sections(sources: list[RequirementsSource]) -> list[str]`. `NewApplication(sections: list[str])`...
[ "Define the `Protocol` with the single method.", "`NewApplication` stores its list and returns a copy on each call.", "`RenewalApplication` concatenates base and extra on each call, so nothing shared is exposed.", "`merged_sections` concatenates all sections and deduplicates with `dict.fromkeys`, which keeps ...
from typing import Protocol class RequirementsSource(Protocol): """Anything that can list the sections an application must contain.""" def required_sections(self) -> list[str]: ... class NewApplication: """A new equipment authorization application.""" def __init__(self, sections: list[str]) -> Non...
from solution import ( NewApplication, RenewalApplication, RequirementsSource, merged_sections, ) def test_protocol_satisfaction() -> None: sources: list[RequirementsSource] = [ NewApplication(["form", "fees"]), RenewalApplication(["form", "label"], ["proof"]), ] assert mer...
from solution import ( NewApplication, RenewalApplication, RequirementsSource, merged_sections, ) def test_new_application_returns_its_sections() -> None: app = NewApplication(["a", "b"]) assert app.required_sections() == ["a", "b"] def test_renewal_application_concatenates_base_and_extra() ...
ds-v4.1-flash
from typing import List, Protocol class RequirementsSource(Protocol): """Anything that can list the sections an application must contain.""" def required_sections(self): # type: () -> List[str] ... class NewApplication(object): """A new equipment authorization application.""" def _...
{ "mutant": "from typing import Protocol\n\nclass RequirementsSource(Protocol):\n \"\"\"Anything that can list the sections an application must contain.\"\"\"\n\n def required_sections(self) -> list[str]:\n ...\n\nclass NewApplication:\n \"\"\"A new equipment authorization application.\"\"\"\n\n de...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-4b3ae8f9220ca4c7
code
trie
ds
parser_plus_model
5
short
{ "kind": "og", "text": "nutria (A large semiaquatic rodent native to South America, commonly known as the coypu)", "sources": [ { "source": "opengloss", "id": "og-glossary:nutria", "headword": "nutria" } ] }
glm-5.3-flash
Our nutria survey records burrow systems as slash-separated paths, for example `"riverbank/entrance/nest"`. Write a dataclass `BurrowNode` with fields `name: str`, `children: dict[str, BurrowNode]`, `visits: int = 0` (decorated with `@dataclass(slots=True)`), and a function `parse_burrows(paths: list[str]) -> BurrowNod...
[ "Create the root node with an empty name.", "For each path, split on `\"/\"` and reject empty segments with `ValueError`.", "Walk or create child nodes segment by segment via `setdefault`.", "Increment `visits` on the leaf node." ]
from dataclasses import dataclass, field @dataclass(slots=True) class BurrowNode: """One node of a nutria burrow trie: a named bank or chamber with children.""" name: str children: dict[str, BurrowNode] = field(default_factory=dict) visits: int = 0 def parse_burrows(paths: list[str]) -> BurrowNode:...
from solution import BurrowNode, parse_burrows def test_root_properties() -> None: root = parse_burrows(["bank/nest"]) assert root.name == "" assert root.visits == 0 def test_nested_children() -> None: root = parse_burrows(["riverbank/entrance/nest"]) assert list(root.children) == ["riverbank"] ...
from solution import BurrowNode, parse_burrows def test_empty_path_list_gives_empty_root() -> None: root = parse_burrows([]) assert isinstance(root, BurrowNode) assert root.name == "" assert root.children == {} assert root.visits == 0 def test_paths_become_nested_children() -> None: root = p...
ds-v4.1-flash
null
{ "mutant": "from dataclasses import dataclass, field\n\n@dataclass(slots=True)\nclass BurrowNode:\n \"\"\"One node of a nutria burrow trie: a named bank or chamber with children.\"\"\"\n name: str\n children: dict[str, BurrowNode] = field(default_factory=dict)\n visits: int = 0\n\ndef parse_burrows(paths...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-d169db866ff836b8
code
business_days
alg
function
3
short
{ "kind": "topic", "text": "grotty (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:grotty", "headword": "grotty" } ] }
glm-5.3-flash
We run a coin-laundry with a strict service schedule, and I need a small helper. Write a function `count_open_days(start: date, end: date, holidays: frozenset[date] | None = None) -> int` in a module `solution.py`. It returns the number of days in the inclusive range `[start, end]` on which the laundry opens. The three...
[ "Validate the range and raise `ValueError` if empty-reversed.", "Normalise `holidays` to a frozenset (empty when None).", "Iterate day by day from start to end, counting weekdays not in holidays." ]
from datetime import date, timedelta def count_open_days(start: date, end: date, holidays: frozenset[date] | None = None) -> int: """Count days in the inclusive range when the laundry opens.""" if start > end: msg = f"invalid range: {start.isoformat()} is after {end.isoformat()}" raise ValueEr...
from datetime import date from solution import count_open_days def test_counts_a_full_week() -> None: start = date(2025, 3, 3) # Monday end = date(2025, 3, 9) # Sunday assert count_open_days(start, end) == 5 def test_single_weekday_counts_one() -> None: assert count_open_days(date(2025, 3, 5), da...
from datetime import date from solution import count_open_days def test_counts_weekdays_in_range() -> None: assert count_open_days(date(2024, 1, 1), date(2024, 1, 5)) == 5 def test_excludes_weekend() -> None: assert count_open_days(date(2024, 1, 6), date(2024, 1, 7)) == 0 def test_excludes_holidays() -> ...
ds-v4.1-flash
from datetime import date, timedelta def count_open_days(start, end, holidays=None): """Count days in the inclusive range when the laundry opens.""" if start > end: raise ValueError("invalid range: %s is after %s" % (start.isoformat(), end.isoformat())) skip = holidays if holidays is not None else...
{ "mutant": "from datetime import date, timedelta\n\ndef count_open_days(start: date, end: date, holidays: frozenset[date] | None=None) -> int:\n \"\"\"Count days in the inclusive range when the laundry opens.\"\"\"\n if start > end:\n msg = f'invalid range: {start.isoformat()} is after {end.isoformat()}...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-0d27ff833d1b1f01
code
stable_sort
alg
class
3
short
{ "kind": "og", "text": "haploid (A cell or nucleus, typically a gamete, that contains a single complete set of chromosomes)", "sources": [ { "source": "opengloss", "id": "og-glossary:haploid", "headword": "haploid" } ] }
glm-5.3-flash
For a cytology lab I need a tiny ranking board for haploid spore samples. Write a class `SporeBoard` with two methods: `add(sample: SporeSample) -> None` and `ranked() -> list[SporeSample]`. Define the frozen dataclass `SporeSample` (fields: `code: str`, `ploidy_score: float`, `mass_pg: float`) in the same module. Orde...
[ "Define a frozen, slotted dataclass `SporeSample`.", "`SporeBoard.add` appends to an internal list.", "`ranked()` sorts a copy by `mass_pg`, then stably by `ploidy_score`, and returns it." ]
from dataclasses import dataclass @dataclass(slots=True, frozen=True) class SporeSample: """A haploid spore measurement.""" code: str ploidy_score: float mass_pg: float class SporeBoard: """Ranks spore samples by ploidy score, then mass, then insertion order.""" def __init__(self) -> None:...
from solution import SporeBoard, SporeSample def test_orders_by_ploidy_score() -> None: board = SporeBoard() board.add(SporeSample("B", 2.0, 1.0)) board.add(SporeSample("A", 1.0, 9.0)) assert [s.code for s in board.ranked()] == ["A", "B"] def test_mass_breaks_ties() -> None: board = SporeBoard()...
from solution import SporeBoard, SporeSample def test_ranks_by_ploidy_score_ascending() -> None: board = SporeBoard() board.add(SporeSample("b", 2.0, 1.0)) board.add(SporeSample("a", 1.0, 1.0)) board.add(SporeSample("c", 3.0, 1.0)) assert [s.code for s in board.ranked()] == ["a", "b", "c"] def t...
ds-v4.1-flash
null
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-4cac941cb552e5bf
code
tree_recursive
ds
class
1
short
{ "kind": "og", "text": "satellites (A natural celestial body that orbits a planet or other primary body)", "sources": [ { "source": "opengloss", "id": "og-glossary:satellites", "headword": "satellites" } ] }
glm-5.3-flash
For a planetarium catalogue, model a moon system as a tree and query it recursively. Write a frozen dataclass `Body` with fields `name: str`, `mass_kg: float`, and `children: tuple["Body", ...] = ()`, and a class `MoonSystem` with two methods: `__init__(self, root: Body) -> None` and `total_mass() -> float`. `total_mas...
[ "Define the frozen dataclass `Body` with a tuple of children.", "`MoonSystem` stores the root.", "`total_mass()` uses an inner recursive walk that adds each node's mass and recurses into children." ]
from dataclasses import dataclass @dataclass(slots=True, frozen=True) class Body: """A body in a moon system, with its orbiting children.""" name: str mass_kg: float children: tuple[Body, ...] = () class MoonSystem: """Queries a tree of bodies rooted at one primary.""" def __init__(self, r...
from solution import Body, MoonSystem def test_leaf_counts_only_itself() -> None: leaf = Body("Luna", 7.3) assert MoonSystem(leaf).total_mass() == 7.3 def test_one_level_sum() -> None: moon_a = Body("Io", 8.9) moon_b = Body("Europa", 4.8) system = MoonSystem(Body("Jupiter", 1898.0, (moon_a, moon...
from solution import Body, MoonSystem def test_leaf_contributes_own_mass() -> None: assert MoonSystem(Body("leaf", 3.5)).total_mass() == 3.5 def test_root_plus_children() -> None: root = Body("root", 10.0, (Body("a", 1.0), Body("b", 2.0))) assert MoonSystem(root).total_mass() == 13.0 def test_deep_tre...
ds-v4.1-flash
null
{ "mutant": "from dataclasses import dataclass\n\n@dataclass(slots=True, frozen=True)\nclass Body:\n \"\"\"A body in a moon system, with its orbiting children.\"\"\"\n name: str\n mass_kg: float\n children: tuple[Body, ...] = ()\n\nclass MoonSystem:\n \"\"\"Queries a tree of bodies rooted at one primar...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [], "b"...
ol5-9b0a10fe89c47f21
code
sparse_vector
ds
formatter
4
short
{ "kind": "topic", "text": "smoked eel (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:smoked eel", "headword": "smoked eel" } ] }
glm-5.3-flash
For a smoked-eel pantry tracker we log stock movements as sparse vectors keyed by shelf index. Write `type SparseVector = dict[int, float]`, `dot(left: SparseVector, right: SparseVector) -> float`, `add(left: SparseVector, right: SparseVector) -> SparseVector`, and `format_vector_report(left: SparseVector, right: Spars...
[ "Implement `dot` as a sum over the intersection of keys.", "Implement `add` over the union of keys with `dict.get` defaults.", "Validate that no index is negative, raising `ValueError`.", "Format aligned rows for the sorted union plus a final dot-product line." ]
"""Sparse integer-indexed vectors and a side-by-side report.""" from itertools import chain type SparseVector = dict[int, float] def dot(left: SparseVector, right: SparseVector) -> float: """Return the dot product over indices present in both vectors.""" return sum(value * right[index] for index, value in l...
from solution import SparseVector, add, dot, format_vector_report def test_dot_common_indices_only() -> None: a: SparseVector = {0: 2.0, 1: 3.0, 9: 100.0} b: SparseVector = {1: 4.0, 2: 5.0} assert dot(a, b) == 12.0 def test_dot_disjoint_is_zero() -> None: a: SparseVector = {0: 2.0} b: SparseVect...
from solution import add, dot, format_vector_report def test_dot_uses_shared_indices_only() -> None: assert dot({0: 2.0, 1: 5.0}, {0: 3.0, 2: 4.0}) == 6.0 def test_dot_with_no_shared_indices_is_zero() -> None: assert dot({}, {0: 1.0}) == 0.0 assert dot({1: 3.0}, {2: 4.0}) == 0.0 def test_add_sums_elem...
ds-v4.1-flash
"""Sparse integer-indexed vectors and a side-by-side report.""" from typing import Dict, List SparseVector = Dict[int, float] def dot(left: SparseVector, right: SparseVector) -> float: """Return the dot product over indices present in both vectors.""" total = 0.0 for index in left.keys(): if ind...
{ "mutant": "\"\"\"Sparse integer-indexed vectors and a side-by-side report.\"\"\"\nfrom itertools import chain\ntype SparseVector = dict[int, float]\n\ndef dot(left: SparseVector, right: SparseVector) -> float:\n \"\"\"Return the dot product over indices present in both vectors.\"\"\"\n return sum((value * rig...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-a0b965b914623389
code
protocol
py
enum_plus_fn
1
short
{ "kind": "public", "text": "vacation accrual", "sources": [] }
glm-5.3-flash
Our HR module accrues vacation days monthly, and the accrual rule depends on employment kind. Write an `Enum` named `EmployeeKind` with members `FULL_TIME`, `PART_TIME`, and `SEASONAL`. Write a `Protocol` named `AccrualPolicy` declaring `standard_days(self, years_of_service: int) -> float`, so any object with that meth...
[ "Define the enum with `auto()` members.", "Define the one-method protocol.", "Validate the service years, then `match` on the enum and scale the policy value." ]
"""Monthly vacation accrual dispatched by employment kind.""" from enum import Enum, auto from typing import Protocol class EmployeeKind(Enum): """Kinds of employment recognised by the accrual rules.""" FULL_TIME = auto() PART_TIME = auto() SEASONAL = auto() class AccrualPolicy(Protocol): """A...
from solution import AccrualPolicy, EmployeeKind, monthly_days class SeniorityPolicy: """Test policy: 1.5 days per completed service year, capped at 15.""" def standard_days(self, years_of_service: int) -> float: return min(15.0, 1.5 * years_of_service) POLICY: AccrualPolicy = SeniorityPolicy() d...
from __future__ import annotations from solution import AccrualPolicy, EmployeeKind, monthly_days class _FixedPolicy: def __init__(self, days: float) -> None: self._days = days def standard_days(self, years_of_service: int) -> float: return self._days def _policy() -> AccrualPolicy: re...
ds-v4.1-flash
"""Monthly vacation accrual dispatched by employment kind.""" from enum import Enum try: from typing import Protocol except ImportError: # pragma: no cover Protocol = object import typing class EmployeeKind(Enum): """Kinds of employment recognised by the accrual rules.""" FULL_TIME = 1 PART_T...
{ "mutant": "\"\"\"Monthly vacation accrual dispatched by employment kind.\"\"\"\nfrom enum import Enum, auto\nfrom typing import Protocol\n\nclass EmployeeKind(Enum):\n \"\"\"Kinds of employment recognised by the accrual rules.\"\"\"\n FULL_TIME = auto()\n PART_TIME = auto()\n SEASONAL = auto()\n\nclass ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-07bba195df32619d
code
decimal
py
function
1
short
{ "kind": "og", "text": "paperback (A book bound with a flexible paper cover rather than a hardcover)", "sources": [ { "source": "opengloss", "id": "og-glossary:paperback", "headword": "paperback" } ] }
glm-5.3-flash
For our small press, paperback orders get a bulk discount that must be computed in exact decimal arithmetic — floating point has already caused cent-level disputes. Write `bulk_price(unit_price: Decimal, copies: int) -> Decimal`. `unit_price` is the list price of one paperback; `copies` is the number of copies ordered....
[ "Validate the copy count.", "Multiply the unit price by the copies.", "Apply the bulk factor when copies >= 10.", "Quantize to cents with `ROUND_HALF_EVEN`." ]
"""Exact bulk pricing for paperback orders.""" from decimal import ROUND_HALF_EVEN, Decimal _CENTS = Decimal("0.01") _BULK_FACTOR = Decimal("0.85") _BULK_THRESHOLD = 10 def bulk_price(unit_price: Decimal, copies: int) -> Decimal: """Total price for a paperback order, discounted from ten copies onward.""" if...
from decimal import Decimal from solution import bulk_price def test_single_copy_no_discount() -> None: assert bulk_price(Decimal("12.50"), 1) == Decimal("12.50") def test_nine_copies_no_discount() -> None: assert bulk_price(Decimal("10.00"), 9) == Decimal("90.00") def test_ten_copies_discounted() -> Non...
from __future__ import annotations from decimal import Decimal from solution import bulk_price def test_copies_below_one_raises() -> None: try: bulk_price(Decimal("10.00"), 0) except ValueError: pass else: raise AssertionError("expected ValueError for 0 copies") try: ...
ds-v4.1-flash
"""Exact bulk pricing for paperback orders.""" from decimal import ROUND_HALF_EVEN, Decimal _CENTS = Decimal("0.01") _BULK_FACTOR = Decimal("0.85") _BULK_THRESHOLD = 10 def bulk_price(unit_price, copies): # type: (Decimal, int) -> Decimal """Total price for a paperback order, discounted from ten copies onwa...
{ "mutant": "\"\"\"Exact bulk pricing for paperback orders.\"\"\"\nfrom decimal import ROUND_HALF_EVEN, Decimal\n_CENTS = Decimal('0.01')\n_BULK_FACTOR = Decimal('0.85')\n_BULK_THRESHOLD = 10\n\ndef bulk_price(unit_price: Decimal, copies: int) -> Decimal:\n \"\"\"Total price for a paperback order, discounted from ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-bcc11395c68d1ba4
code
state_machine
alg
module
3
short
{ "kind": "legal", "text": "Account 184, Clearing accounts (the subject of 18 CFR 367.1840, Conservation of Power and Water Resources)", "sources": [ { "source": "ecfr", "id": "18 CFR 367.1840", "agency": "FEDERAL ENERGY REGULATORY COMMISSION, DEPARTMENT OF ENERGY" } ] }
glm-5.3-flash
We need a tiny ledger module for journal entries in Account 184, a clearing account. An entry moves through the states `DRAFT`, `POSTED`, `DISPUTED`, `CLEARED` (an enum `State`) when the events `POST`, `DISPUTE`, `RESOLVE`, `CLEAR` (an enum `Event`) occur. Write `transition(state: State, event: Event) -> State` driven ...
[ "Declare the two enums and a table keyed by (state, event) pairs.", "`transition` looks the pair up and converts a miss into a ValueError.", "`run_journal` folds the events through `transition` in order.", "`is_settled` is a single identity check." ]
"""State machine for journal entries in a clearing account (Account 184).""" from enum import Enum, auto class State(Enum): """Journal-entry states for the clearing account.""" DRAFT = auto() POSTED = auto() DISPUTED = auto() CLEARED = auto() class Event(Enum): """Events that move an entry...
from solution import Event, State, is_settled, run_journal, transition def test_legal_transitions() -> None: assert transition(State.DRAFT, Event.POST) is State.POSTED assert transition(State.POSTED, Event.DISPUTE) is State.DISPUTED assert transition(State.DISPUTED, Event.RESOLVE) is State.POSTED asse...
from solution import Event, State, is_settled, run_journal, transition def test_transition_legal() -> None: assert transition(State.DRAFT, Event.POST) is State.POSTED assert transition(State.POSTED, Event.DISPUTE) is State.DISPUTED assert transition(State.DISPUTED, Event.RESOLVE) is State.POSTED asser...
ds-v4.1-flash
class State(object): """Journal-entry states for the clearing account.""" DRAFT = "draft" POSTED = "posted" DISPUTED = "disputed" CLEARED = "cleared" class Event(object): """Events that move an entry between states.""" POST = "post" DISPUTE = "dispute" RESOLVE = "resolve" CLE...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-388ebf64f27b9f2c
code
protocol
py
function
1
short
{ "kind": "og", "text": "chincapin (The edible seed of Castanea pumila, a small deciduous tree native to eastern North America)", "sources": [ { "source": "opengloss", "id": "og-glossary:chincapin", "headword": "chincapin" } ] }
glm-5.3-flash
We sort chincapin seeds (the edible nuts of Castanea pumila) by plumpness before packing. Write a protocol `SeedLike` with a single read-only property `grams -> float`, and a top-level function `plumpiest(batch: Sequence[SeedLike]) -> SeedLike` that returns the seed with the greatest `grams` value. The batch is any seq...
[ "Define a structural `Protocol` with one `grams` property so any class with that attribute qualifies without inheritance.", "Guard the empty case and raise `ValueError`.", "Use `max` with `key=lambda s: s.grams` to pick the heaviest seed." ]
from collections.abc import Sequence from typing import Protocol class SeedLike(Protocol): """Anything that exposes an edible seed mass in grams.""" @property def grams(self) -> float: ... def plumpiest(batch: Sequence[SeedLike]) -> SeedLike: """Return the seed in the batch with the greatest mass."...
from solution import plumpiest class Sample: def __init__(self, grams: float) -> None: self.grams = grams def test_picks_heaviest() -> None: batch = [Sample(1.2), Sample(3.4), Sample(2.0)] assert plumpiest(batch).grams == 3.4 def test_accepts_any_structural_type() -> None: class Nut: ...
from solution import SeedLike, plumpiest class Seed: def __init__(self, grams: float) -> None: self._grams = grams @property def grams(self) -> float: return self._grams def test_plumpiest_empty_raises() -> None: batch: list[Seed] = [] try: plumpiest(batch) except Va...
ds-v4.1-flash
from typing import Protocol, Sequence class SeedLike(Protocol): """Anything that exposes an edible seed mass in grams.""" @property def grams(self): # type: ignore[empty-body] ... def plumpiest(batch): """Return the seed in the batch with the greatest mass.""" if not batch: rai...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": [], "b": [] }, ...
ol5-c0b77f4bd4bcd41e
code
dp_lcs
alg
pure_pipeline
5
short
{ "kind": "topic", "text": "cellular manufacturing (a topic in business)", "sources": [ { "source": "opengloss", "id": "og-enc:cellular manufacturing", "headword": "cellular manufacturing" } ] }
glm-5.3-flash
Our plant re-cells its line and I want a small report on how much of the old machine layout survives. Machine layouts are strings of single-letter machine codes, e.g. `"ABCB"`. Write `lcs_length(a: str, b: str) -> int`, `lcs_string(a: str, b: str) -> str`, and a pipeline function `layout_report(old: str, new: str) -> s...
[ "Build the classic DP table of LCS lengths row by row.", "`lcs_length` keeps only two rows and returns the bottom-right cell.", "`lcs_string` rebuilds the full table and walks back from the end, taking diagonal steps on matches and preferring the `i-1` move on ties (this yields the leftmost LCS).", "`layout_r...
def lcs_length(a: str, b: str) -> int: """Return the length of the longest common subsequence of a and b.""" prev = [0] * (len(b) + 1) for char_a in a: cur = [0] for j, char_b in enumerate(b, 1): cur.append(prev[j - 1] + 1 if char_a == char_b else max(prev[j], cur[j - 1])) ...
from solution import layout_report, lcs_length, lcs_string def test_empty_inputs() -> None: assert lcs_length("", "ABC") == 0 assert lcs_length("ABC", "") == 0 assert lcs_string("", "ABC") == "" def test_equal_strings() -> None: assert layout_report("ABC", "ABC") == "keep:3 drop:0 add:0" def test_...
from solution import layout_report, lcs_length, lcs_string def test_lcs_with_empty_string() -> None: assert lcs_length("", "ABC") == 0 assert lcs_length("ABC", "") == 0 assert lcs_string("", "ABC") == "" assert lcs_string("ABC", "") == "" def test_layout_report_equal_layouts() -> None: assert la...
ds-v4.1-flash
def lcs_length(a, b): """Return the length of the longest common subsequence of a and b.""" prev = [0] * (len(b) + 1) for char_a in a: cur = [0] for j in range(len(b)): if char_a == b[j]: cur.append(prev[j] + 1) else: cur.append(max(pre...
{ "mutant": "def lcs_length(a: str, b: str) -> int:\n \"\"\"Return the length of the longest common subsequence of a and b.\"\"\"\n prev = [0] * (len(b) + 1)\n for char_a in a:\n cur = [0]\n for j, char_b in enumerate(b, 1):\n cur.append(prev[j - 1] + 1 if char_a == char_b else max(p...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-e161957a79407349
code
binary_search_answer
alg
generator
4
short
{ "kind": "og", "text": "thickener (A substance added to liquids to increase viscosity, typically used in foods and other products)", "sources": [ { "source": "opengloss", "id": "og-glossary:thickener", "headword": "thickener" } ] }
glm-5.3-flash
For a sauce line I need to compute the smallest whole-gram dose of thickener that reaches a target viscosity. Viscosity is modelled by the module function `viscosity(grams: float) -> float`, defined as `1.0 + 8.0 * grams / (grams + 4.0)`, which increases monotonically. Write a generator `candidate_doses(max_grams: int)...
[ "`candidate_doses` yields whole grams from 0 to `max_grams` via `range`.", "The consumer materialises the candidates (increasing, indexable) for binary search.", "First check reachability at the top of the range and raise `ValueError` if short.", "Standard lower-bound binary search on the viscosity check keep...
from collections.abc import Iterator def viscosity(grams: float) -> float: """Model sauce viscosity in centipoise for a dose of thickener in grams.""" return 1.0 + 8.0 * grams / (grams + 4.0) def candidate_doses(max_grams: int) -> Iterator[int]: """Yield every whole-gram dose from 0 up to max_grams in i...
from solution import candidate_doses, smallest_effective_dose, viscosity def test_candidates_increasing() -> None: assert list(candidate_doses(5)) == [0, 1, 2, 3, 4, 5] def test_zero_dose_suffices() -> None: assert smallest_effective_dose(10, 1.0) == 0 def test_unreachable_raises() -> None: try: ...
from solution import candidate_doses, smallest_effective_dose, viscosity def test_candidate_doses_includes_all_whole_grams() -> None: assert list(candidate_doses(5)) == [0, 1, 2, 3, 4, 5] def test_viscosity_formula_endpoints_and_increase() -> None: assert viscosity(0.0) == 1.0 assert viscosity(4.0) == 5...
ds-v4.1-flash
import math def viscosity(grams): """Model sauce viscosity in centipoise for a dose of thickener in grams.""" return 1.0 + 8.0 * grams / (grams + 4.0) def candidate_doses(max_grams): """Yield every whole-gram dose from 0 up to max_grams in increasing order.""" for dose in range(max_grams + 1): ...
{ "mutant": "from collections.abc import Iterator\n\ndef viscosity(grams: float) -> float:\n \"\"\"Model sauce viscosity in centipoise for a dose of thickener in grams.\"\"\"\n return 1.0 + 8.0 * grams / (grams + 4.0)\n\ndef candidate_doses(max_grams: int) -> Iterator[int]:\n \"\"\"Yield every whole-gram dos...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": true, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-608672a2e03f4d23
code
frozenset_keys
ds
generator
5
short
{ "kind": "og", "text": "canvas (The prepared fabric surface, typically linen or cotton, stretched on a frame and primed for painting)", "sources": [ { "source": "opengloss", "id": "og-glossary:canvas", "headword": "canvas" } ] }
glm-5.3-flash
For a studio inventory of primed canvas sheets we track which pigment pairs produce which blended swatch. Write a generator function `pairings(pigments: Iterable[str]) -> Iterator[frozenset[str]]` that yields every unordered pair of distinct pigment names exactly once, and a function `canvas_swatch(pigments: Iterable[s...
[ "`pairings` de-duplicates the names while keeping first-appearance order.", "It yields `frozenset({first, second})` for every index pair `i < j`.", "`canvas_swatch` iterates the generator and looks each pair up in `recipes`.", "A missing key propagates as `KeyError`; fewer than two names yields nothing." ]
"""Pigment pair recipes for primed canvas sheets.""" from collections.abc import Iterable, Iterator def pairings(pigments: Iterable[str]) -> Iterator[frozenset[str]]: """Yield each unordered pair of distinct pigment names exactly once.""" ordered: list[str] = [] seen: set[str] = set() for name in pig...
from solution import canvas_swatch, pairings def test_unordered_key_matches_both_orders() -> None: recipes = {frozenset({"red", "blue"}): "violet"} assert canvas_swatch(["red", "blue"], recipes) == ["violet"] assert canvas_swatch(["blue", "red"], recipes) == ["violet"] def test_duplicates_collapse() -> ...
from solution import canvas_swatch, pairings def test_pairings_all_once() -> None: pairs = list(pairings(["red", "blue", "green"])) assert pairs == [ frozenset({"red", "blue"}), frozenset({"red", "green"}), frozenset({"blue", "green"}), ] def test_pairings_dedup_names() -> None: ...
ds-v4.1-flash
"""Pigment pair recipes for primed canvas sheets.""" from typing import Dict, Iterable, List, Iterator def pairings(pigments): """Yield each unordered pair of distinct pigment names exactly once.""" ordered = [] seen = set() for name in pigments: if name not in seen: seen.add(name...
{ "mutant": "\"\"\"Pigment pair recipes for primed canvas sheets.\"\"\"\nfrom collections.abc import Iterable, Iterator\n\ndef pairings(pigments: Iterable[str]) -> Iterator[frozenset[str]]:\n \"\"\"Yield each unordered pair of distinct pigment names exactly once.\"\"\"\n ordered: list[str] = []\n seen: set[s...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining":...
ol5-97e062bc3570a46e
code
undo_stack
alg
pure_pipeline
3
short
{ "kind": "topic", "text": "system-wide (a topic in technology)", "sources": [ { "source": "opengloss", "id": "og-enc:system-wide", "headword": "system-wide" } ] }
glm-5.3-flash
For a system-wide settings syncer we need an undo/redo pipeline over plain snapshots. Write `def apply(edit: dict[str, str], state: dict[str, str]) -> dict[str, str]` that returns a new dict with the edit's key/value pairs applied, `def snapshot(state: dict[str, str]) -> tuple[dict[str, str], ...]` that turns a history...
[ "`apply` merges `{**state, **edit}` into a new dict.", "`snapshot` copies each history entry into a tuple.", "`replay` builds a history list: start state plus one state per edit.", "Undo index starts at the end; each undo step decreases it but not below 0; the final state is a copy of `history[index]` (redo e...
type State = dict[str, str] def apply(edit: dict[str, str], state: dict[str, str]) -> dict[str, str]: """Return a new settings state with the edit's pairs layered on top.""" return {**state, **edit} def snapshot(history: list[State]) -> tuple[State, ...]: """Freeze a history into a tuple of independent ...
from solution import apply, replay, snapshot def test_apply_returns_new_dict() -> None: start = {"theme": "dark", "lang": "en"} out = apply({"lang": "fr"}, start) assert out == {"theme": "dark", "lang": "fr"} assert start == {"theme": "dark", "lang": "en"} def test_replay_zero_undo_returns_final() -...
from solution import apply, replay, snapshot def test_apply_returns_new_dict_and_does_not_mutate() -> None: state = {"a": "1", "b": "2"} edit = {"b": "3", "c": "4"} result = apply(edit, state) assert result == {"a": "1", "b": "3", "c": "4"} assert result is not state assert state == {"a": "1",...
ds-v4.1-flash
def apply(edit, state): """Return a new settings state with the edit's pairs layered on top.""" merged = dict(state) for key in edit.keys(): merged[key] = edit[key] return merged def snapshot(history): """Freeze a history into a tuple of independent copies.""" frozen = [] for i in ...
{ "mutant": "type State = dict[str, str]\n\ndef apply(edit: dict[str, str], state: dict[str, str]) -> dict[str, str]:\n \"\"\"Return a new settings state with the edit's pairs layered on top.\"\"\"\n return {**state, **edit}\n\ndef snapshot(history: list[State]) -> tuple[State, ...]:\n \"\"\"Freeze a history...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-b73b2f02b50eb3ad
code
result_type
test
enum_plus_fn
1
short
{ "kind": "public", "text": "vacation accrual", "sources": [] }
glm-5.3-flash
Vacation accrual: employees accrue days per month at a rate that depends on their seniority band. Write an `enum.StrEnum` called `Band` with members `NEW`, `ESTABLISHED`, and `VETERAN`, and `def accrue(band: Band, months: int, *, carried_over: float = 0.0) -> AccrualResult` where `AccrualResult` is a frozen slots datac...
[ "Define the `Band` StrEnum with the three members.", "Map each band to its monthly rate with a dict.", "Validate inputs; on failure return the error result.", "Otherwise compute and round the total into an ok result." ]
from dataclasses import dataclass from enum import StrEnum class Band(StrEnum): """Seniority bands used for vacation accrual rates.""" NEW = "new" ESTABLISHED = "established" VETERAN = "veteran" @dataclass(slots=True, frozen=True) class AccrualResult: """Outcome of an accrual computation: value...
from solution import AccrualResult, Band, accrue def test_new_band_rate() -> None: out = accrue(Band.NEW, 4) assert out == AccrualResult(ok=True, value=5.0) def test_established_band_rate() -> None: assert accrue(Band.ESTABLISHED, 8).value == 14.0 def test_veteran_band_rate() -> None: assert accru...
from solution import AccrualResult, Band, accrue def test_band_values() -> None: assert Band.NEW == "new" assert Band.ESTABLISHED == "established" assert Band.VETERAN == "veteran" def test_rates_for_each_band() -> None: new_result = accrue(Band.NEW, 10) established_result = accrue(Band.ESTABLISH...
ds-v4.1-flash
null
{ "mutant": "from dataclasses import dataclass\nfrom enum import StrEnum\n\nclass Band(StrEnum):\n \"\"\"Seniority bands used for vacation accrual rates.\"\"\"\n NEW = 'new'\n ESTABLISHED = 'established'\n VETERAN = 'veteran'\n\n@dataclass(slots=True, frozen=True)\nclass AccrualResult:\n \"\"\"Outcome ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-c3e14ccf51125f7f
code
shortest_grid_path
alg
function
1
short
{ "kind": "og", "text": "bedder (A person whose occupation is to arrange, replace, and manage the bedding in facilities such as hotels or hospitals)", "sources": [ { "source": "opengloss", "id": "og-glossary:bedder", "headword": "bedder" } ] }
glm-5.3-flash
We run the night shift at St. Anselm's and the ward floor is mapped as a grid of bays; a bay the bedder has already made is walkable, one still stripped is blocked. Write one top-level function `shortest_route(grid: list[list[bool]], start: tuple[int, int], goal: tuple[int, int]) -> int | None` that returns the fewest ...
[ "Unpack the coordinates and reject blocked endpoints with `ValueError`.", "Run breadth-first search from `start`, storing first-arrival step counts in a dict.", "Return the count as soon as `goal` is dequeued; return `None` if the queue empties." ]
from collections import deque def shortest_route( grid: list[list[bool]], start: tuple[int, int], goal: tuple[int, int], ) -> int | None: """Return the fewest steps from start to goal across walkable bays, or None.""" row_start, col_start = start row_goal, col_goal = goal if not grid[row_s...
from solution import shortest_route def test_straight_line() -> None: grid = [[True, True, True]] assert shortest_route(grid, (0, 0), (0, 2)) == 2 def test_detour_around_blocked_bay() -> None: grid = [ [True, False, True], [True, True, True], ] assert shortest_route(grid, (0, 0),...
from solution import shortest_route def test_shortest_route_simple_path() -> None: grid: list[list[bool]] = [ [True, True, True], [True, False, True], [True, True, True], ] assert shortest_route(grid, (0, 0), (2, 2)) == 4 def test_shortest_route_returns_none_when_blocked() -> Non...
ds-v4.1-flash
from collections import deque from typing import List, Optional, Tuple Grid = List[List[bool]] def shortest_route(grid, start, goal): sr, sc = start gr, gc = goal if not grid[sr][sc] or not grid[gr][gc]: raise ValueError("start and goal must be walkable cells") distances = {start: 0} queu...
{ "mutant": "from collections import deque\n\ndef shortest_route(grid: list[list[bool]], start: tuple[int, int], goal: tuple[int, int]) -> int | None:\n \"\"\"Return the fewest steps from start to goal across walkable bays, or None.\"\"\"\n row_start, col_start = start\n row_goal, col_goal = goal\n if not...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-21c0ad057b82d9aa
code
merge_intervals
alg
function
4
short
{ "kind": "og", "text": "ensete (A genus of large herbaceous flowering plants in the family Musaceae native to tropical Africa)", "sources": [ { "source": "opengloss", "id": "og-glossary:ensete", "headword": "ensete" } ] }
glm-5.3-flash
I am logging how long each ensete corm stays in its sprouting bed, and the logs come messy. Write one top-level function `merge_corm_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]` (small private helpers are allowed) that takes day spans and returns the merged coverage. The rules are: (1) an empty input r...
[ "Validate every span, raising `ValueError` on an inverted one.", "Sort the spans by start day.", "Sweep once, extending the last merged span when the current one overlaps or touches it.", "Return the merged spans as a list of tuples." ]
def merge_corm_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]: """Merge overlapping or touching ensete sprouting spans into sorted spans.""" if any(start > end for start, end in spans): raise ValueError("span start must not exceed its end") ordered = sorted(spans) merged: list[list...
from solution import merge_corm_spans def test_empty_input() -> None: assert merge_corm_spans([]) == [] def test_output_is_sorted() -> None: spans = [(9, 12), (1, 3), (5, 7)] assert merge_corm_spans(spans) == [(1, 3), (5, 7), (9, 12)] def test_touching_spans_merge() -> None: assert merge_corm_span...
from solution import merge_corm_spans def test_empty_input() -> None: assert merge_corm_spans([]) == [] def test_sorted_output() -> None: assert merge_corm_spans([(5, 7), (1, 3)]) == [(1, 3), (5, 7)] def test_overlapping_spans_merge() -> None: assert merge_corm_spans([(1, 4), (3, 6)]) == [(1, 6)] ...
ds-v4.1-flash
from typing import List, Tuple def merge_corm_spans(spans): """Merge overlapping or touching ensete sprouting spans into sorted spans.""" # type: (List[Tuple[int, int]]) -> List[Tuple[int, int]] for i in range(len(spans)): start, end = spans[i] if start > end: raise ValueError(...
{ "mutant": "def merge_corm_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"Merge overlapping or touching ensete sprouting spans into sorted spans.\"\"\"\n if any((start > end for start, end in spans)):\n raise ValueError('span start must not exceed its end')\n ordered = sorted(s...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-b6622e886d7fff68
code
matrix_grid
ds
dataclass_plus_fn
2
short
{ "kind": "og", "text": "stratus (A low, uniform cloud layer covering the sky and often producing drizzle or light rain)", "sources": [ { "source": "opengloss", "id": "og-glossary:stratus", "headword": "stratus" } ] }
glm-5.3-flash
We track drizzle over a low stratus layer as a rectangular grid of cloud depths. Write a module with a slots dataclass `StratusField` constructed as `StratusField(depth: list[list[int]])` plus its methods. Rule 1: if the grid is empty or its rows have differing lengths, construction raises `ValueError`; otherwise `dept...
[ "Validate rectangularity in `__post_init__`.", "Bounds-check both indices in `depth_at` and raise `IndexError` with a clear message.", "In `drizzle_cells`, collect only in-bounds orthogonal neighbours per cell.", "Compare the neighbour mean against the threshold and count matches." ]
from dataclasses import dataclass @dataclass(slots=True) class StratusField: """A rectangular grid of drizzle depths under a low cloud layer.""" depth: list[list[int]] def __post_init__(self) -> None: if not self.depth or len({len(row) for row in self.depth}) != 1: msg = "depth must ...
from solution import StratusField def test_depth_at_reads_cells() -> None: field = StratusField([[0, 6], [6, 6]]) assert field.depth_at(0, 1) == 6 assert field.depth_at(1, 0) == 6 def test_depth_at_out_of_bounds() -> None: field = StratusField([[1, 2], [3, 4]]) try: field.depth_at(2, 0) ...
from solution import StratusField def test_empty_grid_raises_value_error() -> None: try: StratusField([]) except ValueError: pass else: raise AssertionError def test_ragged_grid_raises_value_error() -> None: try: StratusField([[1, 2], [3]]) except ValueError: ...
ds-v4.1-flash
class StratusField(object): """A rectangular grid of drizzle depths under a low cloud layer.""" def __init__(self, depth): self.depth = depth if not depth or len(set([len(row) for row in depth])) != 1: raise ValueError("depth must be a non-empty rectangular grid") def depth_at(...
{ "mutant": "from dataclasses import dataclass\n\n@dataclass(slots=True)\nclass StratusField:\n \"\"\"A rectangular grid of drizzle depths under a low cloud layer.\"\"\"\n depth: list[list[int]]\n\n def __post_init__(self) -> None:\n if not self.depth or len({len(row) for row in self.depth}) != 1:\n ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-be59385c03025f26
code
dp_lis
alg
class
5
short
{ "kind": "public", "text": "postal rates", "sources": [] }
glm-5.3-flash
Build a small rate lookup for parcel post. Write a class `RateBook` with `__init__(self) -> None`, `add(self, zone: str, weight: int, price: int) -> None`, and `chain_length(self, zone: str) -> int`. `add` records a weight/price pair for a zone. `chain_length` returns the length of the longest strictly increasing run o...
[ "Store per-zone lists of `(weight, price)` pairs in insertion order.", "In `add`, reject duplicate weights for the zone with `ValueError`.", "In `chain_length`, raise `KeyError` for unknown zones.", "Stable-sort the entries by weight and extract the price sequence.", "Run patience-style LIS with `bisect_lef...
from bisect import bisect_left class RateBook: """Postal rates per zone with longest rising price chains.""" def __init__(self) -> None: self._rates: dict[str, list[tuple[int, int]]] = {} def add(self, zone: str, weight: int, price: int) -> None: """Record one weight and price for a zone...
from solution import RateBook def build() -> RateBook: book = RateBook() book.add("north", 1, 5) book.add("north", 3, 9) book.add("north", 2, 7) return book def test_duplicate_weight_rejected() -> None: book = build() try: book.add("north", 1, 2) except ValueError: pa...
from solution import RateBook def test_duplicate_zone_weight_raises_value_error() -> None: book = RateBook() book.add("north", 1, 10) try: book.add("north", 1, 20) except ValueError: pass else: raise AssertionError def test_unknown_zone_raises_key_error() -> None: boo...
ds-v4.1-flash
from bisect import bisect_left class RateBook(object): """Postal rates per zone with longest rising price chains.""" def __init__(self): self._rates = {} def add(self, zone, weight, price): entries = self._rates.setdefault(zone, []) for entry_weight, _ in entries: if ...
{ "mutant": "from bisect import bisect_left\n\nclass RateBook:\n \"\"\"Postal rates per zone with longest rising price chains.\"\"\"\n\n def __init__(self) -> None:\n self._rates: dict[str, list[tuple[int, int]]] = {}\n\n def add(self, zone: str, weight: int, price: int) -> None:\n \"\"\"Record...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-2e80e74e851d86c8
code
functools
py
enum_plus_fn
2
short
{ "kind": "og", "text": "filament (A slender threadlike part or structure that forms a long thin strand)", "sources": [ { "source": "opengloss", "id": "og-glossary:filament", "headword": "filament" } ] }
glm-5.3-flash
Small helper module for a 3-D printer filament workshop. Define an `enum.Enum` subclass `Material` with members `PLA`, `PETG` and `ABS`; give each member attributes `low` and `high` (an inclusive nozzle temperature window) by constructing members from 2-tuples and implementing `Material.__init__`. Write `def nozzle_win...
[ "Build the `Material` enum whose `__init__` unpacks the low and high window bounds.", "`nozzle_window` validates `boost >= 0`, then shifts both bounds.", "Bind `PLA_WINDOW` with `functools.partial` at import time.", "Order spools with `total_ordering` over a single `__lt__`.", "Sum spool plus remnants with ...
"""Nozzle temperature windows and spool arithmetic for printer filament.""" import enum import functools import operator from dataclasses import dataclass class Material(enum.Enum): """Filament materials, each with an inclusive nozzle temperature window.""" PLA = (190, 220) PETG = (220, 250) ABS = (...
from solution import PLA_WINDOW, Material, Spool, nozzle_window, total_filament def test_window_base() -> None: assert nozzle_window(Material.PETG) == (220, 250) def test_window_boost() -> None: assert nozzle_window(Material.ABS, boost=4) == (234, 264) def test_boost_negative() -> None: try: n...
from solution import PLA_WINDOW, Material, Spool, nozzle_window, total_filament def test_material_windows() -> None: assert Material.PLA.low == 190 assert Material.PLA.high == 220 assert Material.PETG.low == 220 assert Material.PETG.high == 250 assert Material.ABS.low == 230 assert Material.AB...
ds-v4.1-flash
"""Nozzle temperature windows and spool arithmetic for printer filament.""" import functools import operator class Material(object): """Filament materials, each with an inclusive nozzle temperature window.""" def __init__(self, low, high): self.low = low self.high = high Material.PLA = Mat...
{ "mutant": "\"\"\"Nozzle temperature windows and spool arithmetic for printer filament.\"\"\"\nimport enum\nimport functools\nimport operator\nfrom dataclasses import dataclass\n\nclass Material(enum.Enum):\n \"\"\"Filament materials, each with an inclusive nozzle temperature window.\"\"\"\n PLA = (190, 221)\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-bbadacfae5648720
code
flatten
alg
stateful_class
5
short
{ "kind": "legal", "text": "Amendments to application (the subject of 38 CFR 59.121, Pensions, Bonuses, and Veterans' Relief)", "sources": [ { "source": "ecfr", "id": "38 CFR 59.121", "agency": "DEPARTMENT OF VETERANS AFFAIRS" } ] }
glm-5.3-flash
A veterans' office stores amendment text for an application as arbitrarily nested lists of strings and integers. Write a class `AmendmentFile` with `__init__(self) -> None`, `add(self, entry: Entry) -> None`, `flat(self) -> Iterator[str]`, and `summary(self) -> tuple[int, int]`, where `Entry` is a recursive type alias ...
[ "Declare the recursive alias `Entry` with the `type` statement.", "`AmendmentFile` keeps a private `list[Entry]` of sections.", "A module-level recursive generator `_walk` yields string leaves and recurses into lists, skipping ints.", "`flat` delegates to `_walk`; `summary` counts sections and leaves." ]
"""Track amendment text for an application and flatten it on demand.""" from collections.abc import Iterator type Entry = str | int | list["Entry"] def _walk(items: list[Entry]) -> Iterator[str]: """Yield the string leaves of a nested entry list, skipping integer leaves.""" for item in items: if isi...
from solution import AmendmentFile def test_flat_strings_in_order() -> None: f = AmendmentFile() f.add(["pension", 7, ["bonus", ["aid"]]]) f.add("last") assert list(f.flat()) == ["pension", "bonus", "aid", "last"] def test_int_leaves_skipped() -> None: f = AmendmentFile() f.add([1, [2, ["x",...
from solution import AmendmentFile, Entry def test_flat_fresh_file_is_empty_and_summary_is_zero() -> None: amendment_file = AmendmentFile() assert list(amendment_file.flat()) == [] assert amendment_file.summary() == (0, 0) def test_add_preserves_top_level_order() -> None: amendment_file = AmendmentF...
ds-v4.1-flash
"""Track amendment text for an application and flatten it on demand.""" from typing import Iterator, List, Tuple, Union Entry = Union[str, int, List["Entry"]] def _walk(items): # type: (List[Entry]) -> Iterator[str] """Yield the string leaves of a nested entry list, skipping integer leaves.""" for item i...
{ "mutant": "\"\"\"Track amendment text for an application and flatten it on demand.\"\"\"\nfrom collections.abc import Iterator\ntype Entry = str | int | list['Entry']\n\ndef _walk(items: list[Entry]) -> Iterator[str]:\n \"\"\"Yield the string leaves of a nested entry list, skipping integer leaves.\"\"\"\n for...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-267eea15dcc2f70f
code
match_statement
py
dataclass_plus_fn
2
short
{ "kind": "og", "text": "android (A humanoid robot designed to resemble and imitate humans in form and behavior, typically capable of perception, manipulation, and...)", "sources": [ { "source": "opengloss", "id": "og-glossary:android", "headword": "android" } ] }
glm-5.3-flash
We are modelling android chassis for a repair shop. Write a dataclass `Android` with `__slots__` and fields `serial: str`, `arms: int`, `battery_pct: int`, plus `def triage(bot: Android) -> str` and `def needs_parts(bot: Android) -> bool`. Rules: (1) `triage` uses a `match` on the bot with class patterns: an `Android` ...
[ "Define the slotted dataclass with `battery_pct` validated in `__post_init__`.", "In `triage`, match on `Android(arms=0, battery_pct=0)`, then guard on low battery, then arms count.", "Implement `needs_parts` by reusing the same patterns via `triage`." ]
"""Android chassis triage rules.""" from dataclasses import dataclass @dataclass(slots=True) class Android: """An android chassis awaiting service.""" serial: str arms: int battery_pct: int def __post_init__(self) -> None: if not 0 <= self.battery_pct <= 100: raise ValueErro...
from solution import Android, needs_parts, triage def test_ready() -> None: assert triage(Android("AX-1", 2, 80)) == "ready" def test_scrap() -> None: assert triage(Android("AX-2", 0, 0)) == "scrap" def test_charge_takes_priority_over_refit() -> None: assert triage(Android("AX-3", 3, 10)) == "charge" ...
from solution import Android, needs_parts, triage def test_triage_scrap_when_no_arms_and_empty_battery() -> None: bot = Android("S1", arms=0, battery_pct=0) assert triage(bot) == "scrap" def test_triage_charge_when_battery_below_twenty() -> None: assert triage(Android("S2", arms=2, battery_pct=19)) == "...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Android chassis triage rules.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Android:\n \"\"\"An android chassis awaiting service.\"\"\"\n serial: str\n arms: int\n battery_pct: int\n\n def __post_init__(self) -> None:\n if not 0 <= self.battery_pct ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-b53f77db9a859766
code
edge_cases
test
parser_plus_model
5
short
{ "kind": "og", "text": "fleabag (A lodging facility that is very dirty and of poor quality, typically dilapidated and inadequately maintained)", "sources": [ { "source": "opengloss", "id": "og-glossary:fleabag", "headword": "fleabag" } ] }
glm-5.3-flash
I'm cataloguing a very shabby guest house and need the room list parsed. Write `parse_rooms(entries: list[str]) -> list[Room]`, plus a dataclass `Room` with fields `number: int`, `floor: int`, `nightly: int`. Each entry is a string of the form `"number;floor;nightly"`, for example `"12;2;45"`. The function returns the ...
[ "Iterate over entries, strip and split each on `\";\"`.", "Reject any entry whose field count is not three, or whose fields do not parse as ints, with `ValueError`.", "Track seen room numbers in a set and reject duplicates.", "Reject non-positive nightly prices.", "Build `Room` records and return them sorte...
"""Parsing of room listings for a run-down lodging house.""" from dataclasses import dataclass @dataclass(slots=True) class Room: """One rentable room with its floor and nightly price.""" number: int floor: int nightly: int def parse_rooms(entries: list[str]) -> list[Room]: """Parse "number;fl...
from solution import Room, parse_rooms def test_empty_input() -> None: assert parse_rooms([]) == [] def test_single_entry() -> None: assert parse_rooms(["7;1;30"]) == [Room(number=7, floor=1, nightly=30)] def test_sorted_by_number() -> None: rooms = parse_rooms(["9;2;40", "3;0;25"]) assert [room.n...
from solution import Room, parse_rooms def test_parse_rooms_empty() -> None: assert parse_rooms([]) == [] def test_parse_rooms_single_entry() -> None: assert parse_rooms(["12;2;45"]) == [Room(12, 2, 45)] def test_parse_rooms_sorted_by_number() -> None: assert parse_rooms(["12;2;45", "3;1;30"]) == [ ...
ds-v4.1-flash
"""Parsing of room listings for a run-down lodging house.""" from typing import List class Room(object): """One rentable room with its floor and nightly price.""" def __init__(self, number, floor, nightly): self.number = number self.floor = floor self.nightly = nightly def __eq_...
{ "mutant": "\"\"\"Parsing of room listings for a run-down lodging house.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Room:\n \"\"\"One rentable room with its floor and nightly price.\"\"\"\n number: int\n floor: int\n nightly: int\n\ndef parse_rooms(entries: list[str]) -> li...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b...
ol5-35a8758b1f805c31
code
enum
py
class
1
short
{ "kind": "og", "text": "taproot (The main root of a plant that grows downward and anchors the plant)", "sources": [ { "source": "opengloss", "id": "og-glossary:taproot", "headword": "taproot" } ] }
glm-5.3-flash
For a small plant-growth simulation I need soil and root types. Write an enum `Soil` with members `TOPSOIL`, `CLAY` and `BEDROCK` and give it a method `hold(self, depth: float) -> float` that returns the force (in newtons) needed to push `depth` centimetres into that soil, using per-soil factors 0.4, 1.8 and 6.0 respec...
[ "Define `Soil` with three members and a `hold` method backed by a per-member factor mapping.", "Define `Taproot` as a slots dataclass with `name`, `depth_cm` and `tension_limit`.", "`grow` checks the force before mutating, so a rejected grow leaves state intact.", "`anchor_score` and `tip_depth` are pure read...
from dataclasses import dataclass from enum import Enum, auto _FACTORS: dict[str, float] = {"TOPSOIL": 0.4, "CLAY": 1.8, "BEDROCK": 6.0} class Soil(Enum): """A soil layer a root can grow through.""" TOPSOIL = auto() CLAY = auto() BEDROCK = auto() def hold(self, depth: float) -> float: "...
from solution import Soil, Taproot def test_hold_factors() -> None: assert Soil.TOPSOIL.hold(10.0) == 4.0 assert Soil.CLAY.hold(10.0) == 18.0 assert Soil.BEDROCK.hold(10.0) == 60.0 def test_grow_adds_depth() -> None: root = Taproot("carrot") force = root.grow(Soil.TOPSOIL, 50.0) assert force...
from solution import Soil, Taproot def test_hold_uses_per_soil_factors() -> None: assert Soil.TOPSOIL.hold(10.0) == 4.0 assert Soil.CLAY.hold(10.0) == 18.0 assert Soil.BEDROCK.hold(10.0) == 60.0 def test_grow_returns_force_and_adds_depth() -> None: root = Taproot("main", 0.0, 100.0) assert root....
ds-v4.1-flash
from enum import Enum, auto class Soil(Enum): """A soil layer a root can grow through.""" TOPSOIL = auto() CLAY = auto() BEDROCK = auto() def hold(self, depth): """Return the force needed to push depth centimetres into this soil.""" factors = {Soil.TOPSOIL: 0.4, Soil.CLAY: 1.8, S...
{ "mutant": "from dataclasses import dataclass\nfrom enum import Enum, auto\n_FACTORS: dict[str, float] = {'TOPSOIL': 0.4, 'CLAY': 1.8, 'BEDROCK': 6.0}\n\nclass Soil(Enum):\n \"\"\"A soil layer a root can grow through.\"\"\"\n TOPSOIL = auto()\n CLAY = auto()\n BEDROCK = auto()\n\n def hold(self, depth...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": ...
ol5-4ba7287ba6b99ca2
code
star_unpacking
py
stateful_class
1
short
{ "kind": "public", "text": "bird counts", "sources": [] }
glm-5.3-flash
I keep field notes of bird counts and want a small tally class. Write a class `Flock` with `__init__(self, site: str)`, `record(self, species: str, count: int) -> None` which adds `count` to that species' running total, `forget(self, first: str, *rest: str) -> None` which removes one or more species from the tally, and...
[ "Store the tally in a plain `dict[str, int]` created in `__init__`.", "`record` validates the count and accumulates into the dict.", "`forget` takes the first name plus `*rest` and drops each name if present.", "`leading` filters zero counts unless `keep_zero`, sorts by `(-count, name)`, then destructures `(f...
class Flock: """Bird counts per species for one survey site.""" def __init__(self, site: str) -> None: """Start an empty tally for the given site.""" self.site = site self.counts: dict[str, int] = {} def record(self, species: str, count: int) -> None: """Add count individua...
from solution import Flock def test_record_accumulates() -> None: flock = Flock("marsh") flock.record("heron", 2) flock.record("heron", 3) assert flock.counts == {"heron": 5} def test_negative_count_raises() -> None: flock = Flock("marsh") try: flock.record("heron", -1) except Va...
from solution import Flock def test_record_and_leading_order() -> None: flock = Flock("pond") flock.record("duck", 2) flock.record("goose", 5) flock.record("swan", 3) assert flock.leading() == ("goose", ["swan", "duck"]) def test_ties_are_broken_alphabetically() -> None: flock = Flock("pond"...
ds-v4.1-flash
class Flock(object): """Bird counts per species for one survey site.""" def __init__(self, site): """Start an empty tally for the given site.""" self.site = site self.counts = {} def record(self, species, count): """Add count individuals of a species to the tally.""" ...
{ "mutant": "class Flock:\n \"\"\"Bird counts per species for one survey site.\"\"\"\n\n def __init__(self, site: str) -> None:\n \"\"\"Start an empty tally for the given site.\"\"\"\n self.site = site\n self.counts: dict[str, int] = {}\n\n def record(self, species: str, count: int) -> N...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-b8705074b9158417
code
decimal
py
stateful_class
6
short
{ "kind": "public", "text": "inspection schedules", "sources": [] }
glm-5.3-flash
Inspection teams bill sites in exact money amounts, so floats are out; use `decimal.Decimal` with explicit rounding. Write a class `InspectionLedger` with `record(self, site: str, fee: Decimal) -> None`, `apply_late_penalty(self, site: str) -> None`, `waive(self, site: str) -> None` and `summary(self) -> dict[str, Deci...
[ "Keep a private dict from site name to Decimal fee.", "`record` validates the sign and quantizes with ROUND_HALF_EVEN before storing.", "`apply_late_penalty` computes 5%, quantizes the penalty with ROUND_UP, then adds.", "`waive` pops the site, raising ValueError if it is absent.", "A shared helper raises t...
"""Inspection schedule billing with exact decimal arithmetic.""" from decimal import ROUND_HALF_EVEN, ROUND_UP, Decimal _CENTS = Decimal("0.01") class InspectionLedger: """Records inspection fees per site and adjusts them with rounded decimals.""" def __init__(self) -> None: self._fees: dict[str, D...
from decimal import Decimal from solution import InspectionLedger def test_record_quantizes_half_even() -> None: ledger = InspectionLedger() ledger.record("barn", Decimal("10.005")) ledger.record("shed", Decimal("10.015")) assert ledger.summary() == {"barn": Decimal("10.00"), "shed": Decimal("10.02")...
from decimal import Decimal from solution import InspectionLedger def test_record_quantizes_half_even() -> None: ledger = InspectionLedger() ledger.record("a", Decimal("10.005")) ledger.record("b", Decimal("10.015")) assert ledger.summary() == { "a": Decimal("10.00"), "b": Decimal("10...
ds-v4.1-flash
"""Inspection schedule billing with exact decimal arithmetic.""" from decimal import ROUND_HALF_EVEN, ROUND_UP, Decimal _CENTS = Decimal("0.01") class InspectionLedger(object): """Records inspection fees per site and adjusts them with rounded decimals.""" def __init__(self): self._fees = {} # type:...
{ "mutant": "\"\"\"Inspection schedule billing with exact decimal arithmetic.\"\"\"\nfrom decimal import ROUND_HALF_EVEN, ROUND_UP, Decimal\n_CENTS = Decimal('0.01')\n\nclass InspectionLedger:\n \"\"\"Records inspection fees per site and adjusts them with rounded decimals.\"\"\"\n\n def __init__(self) -> None:\...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-f3c221531adf100e
code
hashable_value
py
generator
6
short
{ "kind": "legal", "text": "Outside containers of foreign products; marking and labeling; application of official inspection legend (the subject of 9 CFR 557.15, Animals and Animal Products)", "sources": [ { "source": "ecfr", "id": "9 CFR 557.15", "agency": "FOOD SAFETY AND INSPECTION SERVIC...
glm-5.3-flash
For a customs checklist on containers of foreign product, model each container label as a frozen dataclass `Label` with fields `mark: str` and `legended: bool`. Write a generator function `missing_legend(labels: list[Label]) -> Iterator[Label]` and a consumer `tally_missing(labels: list[Label]) -> dict[str, int]` that ...
[ "Define `Label` as a frozen, slotted dataclass so it is hashable.", "The generator walks the list, skipping legended labels and already-seen equal labels kept in a set.", "The consumer iterates the generator, raising `ValueError` on an empty mark.", "It accumulates `mark -> count` in a dict." ]
"""Inspection-legend checks on container labels of foreign product.""" from collections.abc import Iterator from dataclasses import dataclass @dataclass(frozen=True, slots=True) class Label: """One container label: its mark text and whether the legend is applied.""" mark: str legended: bool def missin...
from solution import Label, missing_legend, tally_missing def test_yields_only_unlegended_in_order() -> None: labels = [Label("A7", True), Label("B2", False), Label("C9", False)] assert list(missing_legend(labels)) == [Label("B2", False), Label("C9", False)] def test_equal_labels_yielded_once() -> None: ...
from solution import Label, missing_legend, tally_missing def test_missing_legend_filters_and_deduplicates() -> None: labels = [ Label("A", False), Label("B", True), Label("A", False), Label("B", False), Label("A", True), ] assert list(missing_legend(labels)) == [La...
ds-v4.1-flash
import typing class Label(object): """One container label: its mark text and whether the legend is applied.""" def __init__(self, mark, legended): # type: (str, bool) -> None self.mark = mark self.legended = legended def __eq__(self, other): # type: (object) -> bool ...
{ "mutant": "\"\"\"Inspection-legend checks on container labels of foreign product.\"\"\"\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass Label:\n \"\"\"One container label: its mark text and whether the legend is applied.\"\"\"\n mark: str\...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-75ecb3610a2dc0dd
code
queue_fifo
ds
generator
4
short
{ "kind": "legal", "text": "Allocation of marketing allotments to processors (the subject of 7 CFR 1435.306, Agriculture)", "sources": [ { "source": "ecfr", "id": "7 CFR 1435.306", "agency": "COMMODITY CREDIT CORPORATION, DEPARTMENT OF AGRICULTURE" } ] }
glm-5.3-flash
For a 7 CFR 1435.306-style exercise, processors line up for marketing allotments and grants are handed out first in, first out. Write a generator `stream_allotments(pending: deque[tuple[str, int]], pool: int) -> Iterator[tuple[str, int]]` that yields `(processor, granted)` pairs, and a function `totals(pending: deque[t...
[ "Take the pending queue as a deque and pop from the left, which gives FIFO order.", "On each pop, reject non-positive wants with ValueError.", "Grant `min(want, remaining pool)` and decrease the pool by that amount.", "Stop the loop when the queue is empty or the pool is exhausted; `totals` sums the stream in...
"""FIFO allocation of marketing allotments to processors.""" from collections import deque from collections.abc import Iterator def stream_allotments(pending: deque[tuple[str, int]], pool: int) -> Iterator[tuple[str, int]]: """Yield (processor, granted) pairs in queue order until the pool runs out.""" remain...
from collections import deque from solution import stream_allotments, totals def test_fifo_order() -> None: queue: deque[tuple[str, int]] = deque([("acme", 10), ("brix", 10)]) pairs = list(stream_allotments(queue, 100)) assert pairs == [("acme", 10), ("brix", 10)] def test_grant_truncated_at_pool() -> ...
from collections import deque from solution import stream_allotments, totals def test_stream_serves_in_queue_order() -> None: pending = deque([("a", 10), ("b", 20)]) assert list(stream_allotments(pending, 100)) == [("a", 10), ("b", 20)] def test_stream_truncates_grant_to_pool() -> None: pending = deque...
ds-v4.1-flash
"""FIFO allocation of marketing allotments to processors.""" from collections import deque from typing import Dict, Iterator, List, Tuple def stream_allotments(pending, pool): # type: (deque, int) -> Iterator[Tuple[str, int]] """Yield (processor, granted) pairs in queue order until the pool runs out.""" ...
{ "mutant": "\"\"\"FIFO allocation of marketing allotments to processors.\"\"\"\nfrom collections import deque\nfrom collections.abc import Iterator\n\ndef stream_allotments(pending: deque[tuple[str, int]], pool: int) -> Iterator[tuple[str, int]]:\n \"\"\"Yield (processor, granted) pairs in queue order until the p...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_...
ol5-5eec577094860526
code
slots_class
py
stateful_class
4
short
{ "kind": "topic", "text": "roman numerals (a topic in mathematics)", "sources": [ { "source": "opengloss", "id": "og-enc:roman numerals", "headword": "roman numerals" } ] }
glm-5.3-flash
Build a small roman-numeral accumulator. Write a class `RomanSum` with `__slots__ = ("total",)`, an `__init__` starting at zero, `add(self, numeral: str) -> None`, `take_away(self, numeral: str) -> None`, `summary(self) -> str` and a `__repr__`. `add` and `take_away` accept subtractive roman numerals built from `I V X ...
[ "Keep a value table for the letters and parse right to left, subtracting letters smaller than the running peak.", "`_to_int` validates letters and rejects empty input with ValueError.", "`_to_roman` builds subtractive notation greedily from a descending step table.", "`RomanSum` stores only `total` in slots; ...
"""A running total fed by roman numerals, held in a slotted class.""" _VALUES: dict[str, int] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100} _STEPS: tuple[tuple[int, str], ...] = ( (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ) ...
from solution import RomanSum def test_add_and_summary() -> None: tally = RomanSum() tally.add("XIV") assert tally.summary() == "total=14 (XIV)" def test_subtractive_parse() -> None: tally = RomanSum() tally.add("XC") assert tally.total == 90 def test_unknown_letter_raises() -> None: t...
from solution import RomanSum def test_fresh_repr_is_exact() -> None: assert repr(RomanSum()) == "RomanSum(total=0)" def test_add_and_summary_use_subtractive_notation() -> None: roman = RomanSum() roman.add("X") roman.add("IV") assert roman.total == 14 assert roman.summary() == "total=14 (XI...
ds-v4.1-flash
"""A running total fed by roman numerals, held in a slotted class.""" _VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100} _STEPS = ( (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ) def _to_int(numeral): """Parse a roman numeral with subtractive pai...
{ "mutant": "\"\"\"A running total fed by roman numerals, held in a slotted class.\"\"\"\n_VALUES: dict[str, int] = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100}\n_STEPS: tuple[tuple[int, str], ...] = ((100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))\n\ndef _to_int(nu...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-0592a27158b32f42
code
priority_queue_ties
ds
validator
3
short
{ "kind": "topic", "text": "supersizes (a topic in everyday life)", "sources": [ { "source": "opengloss", "id": "og-enc:supersizes", "headword": "supersizes" } ] }
glm-5.3-flash
At the fairground snack bar, supersized orders get checked before the fryer sees them. Write a dataclass `Order` with fields `item: str`, `size: str`, `qty: int`, and a function `check_supersizes(orders: list[Order]) -> list[str]`. Collect every problem, then drain a heap of `(priority, sequence, message)` tuples so th...
[ "Walk the orders with `enumerate` for the sequence counter.", "Push `(priority, next(count()), message)` into a heap for each detected problem; one order may yield several messages.", "Pop the heap until empty and collect the messages in priority order, ties resolved by the sequence counter.", "Return the col...
"""Validator for supersized snack orders, reporting problems in priority order.""" import heapq from dataclasses import dataclass from itertools import count _ALLOWED = {"small", "medium", "large", "supersize"} @dataclass(slots=True) class Order: """One snack order line with an item name, a size and a quantity....
from solution import Order, check_supersizes def test_nonpositive_quantity_first() -> None: orders = [Order(item="fries", size="supersize", qty=0)] assert check_supersizes(orders) == ["fries: nonpositive quantity 0"] def test_unknown_size_message() -> None: orders = [Order(item="slush", size="colossal",...
from solution import Order, check_supersizes def test_nonpositive_quantity_message() -> None: assert check_supersizes([Order("fries", "small", 0)]) == ["fries: nonpositive quantity 0"] assert check_supersizes([Order("fries", "small", -2)]) == ["fries: nonpositive quantity -2"] def test_unknown_size_message(...
ds-v4.1-flash
"""Validator for supersized snack orders, reporting problems in priority order.""" import heapq from typing import List _ALLOWED = set(["small", "medium", "large", "supersize"]) class Order(object): """One snack order line with an item name, a size and a quantity.""" def __init__(self, item, size, qty): ...
{ "mutant": "\"\"\"Validator for supersized snack orders, reporting problems in priority order.\"\"\"\nimport heapq\nfrom dataclasses import dataclass\nfrom itertools import count\n_ALLOWED = {'small', 'medium', 'large', 'supersize'}\n\n@dataclass(slots=True)\nclass Order:\n \"\"\"One snack order line with an item...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, ...
ol5-e6f883bab16e882f
code
business_days
alg
enum_plus_fn
3
short
{ "kind": "public", "text": "utility rate schedules", "sources": [] }
glm-5.3-flash
For our small power utility I need weekend-aware billing. Write an enum `RateSeason` with members `WINTER` and `SUMMER`, and a function `service_charge(start: date, end: date, holidays: frozenset[date], season: RateSeason) -> int` that totals a per-day service charge over business days in the inclusive range `start..en...
[ "Validate that `start <= end`, raising `ValueError` otherwise.", "Build the inclusive list of dates from `start` to `end`.", "Keep a date only if its weekday is below 5 and it is not in `holidays`.", "Dispatch on `RateSeason` to select the daily rate, then sum days times rate." ]
"""Business-day service charges for utility rate schedules.""" from datetime import date, timedelta from enum import Enum, auto class RateSeason(Enum): """Which rate schedule applies.""" WINTER = auto() SUMMER = auto() _DAILY_RATE: dict[RateSeason, int] = { RateSeason.WINTER: 200, RateSeason.S...
from datetime import date from solution import RateSeason, service_charge def test_single_business_day() -> None: wed = date(2025, 6, 4) assert service_charge(wed, wed, frozenset(), RateSeason.SUMMER) == 150 def test_weekend_skipped() -> None: sat = date(2025, 6, 7) sun = date(2025, 6, 8) asser...
from datetime import date from solution import RateSeason, service_charge def test_single_weekday_winter_charge() -> None: charge = service_charge(date(2024, 1, 1), date(2024, 1, 1), frozenset(), RateSeason.WINTER) assert charge == 200 def test_single_weekday_summer_charge() -> None: charge = service_c...
ds-v4.1-flash
"""Business-day service charges for utility rate schedules.""" from datetime import date, timedelta from enum import Enum, auto class RateSeason(Enum): """Which rate schedule applies.""" WINTER = auto() SUMMER = auto() _DAILY_RATE = { RateSeason.WINTER: 200, RateSeason.SUMMER: 150, } def ser...
{ "mutant": "\"\"\"Business-day service charges for utility rate schedules.\"\"\"\nfrom datetime import date, timedelta\nfrom enum import Enum, auto\n\nclass RateSeason(Enum):\n \"\"\"Which rate schedule applies.\"\"\"\n WINTER = auto()\n SUMMER = auto()\n_DAILY_RATE: dict[RateSeason, int] = {RateSeason.WINT...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining"...
ol5-ab079a3be9cbae72
code
async_basics
py
class
1
short
{ "kind": "topic", "text": "becomingly (a topic in arts)", "sources": [ { "source": "opengloss", "id": "og-enc:becomingly", "headword": "becomingly" } ] }
glm-5.3-flash
I'm putting together a small performance-art piece about "becoming" — a figure slowly transforms on stage through several acts. Write a class `Becoming` with `__init__(self, delays: dict[str, float]) -> None`, an `async def act(self, name: str) -> str` method, and an `async def perform(self, acts: list[str]) -> list[st...
[ "Store the delay table on the instance.", "`act` sleeps for its delay (defaulting to 0.0) and returns its name.", "`perform` builds one coroutine per act and gathers them.", "`gather` preserves argument order in its result, giving the required order." ]
import asyncio class Becoming: """Stage a gradual on-stage transformation from concurrent acts.""" def __init__(self, delays: dict[str, float]) -> None: self._delays = delays async def act(self, name: str) -> str: """Hold one act for its assigned delay, then report it done.""" aw...
import asyncio from solution import Becoming def test_perform_preserves_order() -> None: b = Becoming({"dawn": 0.03, "bloom": 0.0, "hush": 0.01}) assert asyncio.run(b.perform(["dawn", "bloom", "hush"])) == ["dawn", "bloom", "hush"] def test_perform_single_act() -> None: b = Becoming({"solo": 0.0}) ...
import asyncio from solution import Becoming def test_act_returns_name() -> None: async def run() -> None: stage = Becoming({"wake": 0.0}) assert await stage.act("wake") == "wake" asyncio.run(run()) def test_act_missing_delay_returns_name() -> None: async def run() -> None: sta...
ds-v4.1-flash
import asyncio from typing import Dict, List class Becoming(object): """Stage a gradual on-stage transformation from concurrent acts.""" def __init__(self, delays): # type: (Dict[str, float]) -> None self._delays = delays async def act(self, name): # type: (str) -> str aw...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-44fec471293e0c03
code
connected_components
alg
pure_pipeline
5
short
{ "kind": "og", "text": "chalkpit (a quarry for chalk)", "sources": [ { "source": "opengloss", "id": "og-glossary:chalkpit", "headword": "chalkpit" } ] }
glm-5.3-flash
Our chalkpit museum has a map of underground galleries joined by tunnels, and visitors keep asking which pits you can reach from a given entrance. Write two small pure functions and one pipeline function. `build_pits(tunnels: list[tuple[str, str]]) -> dict[str, set[str]]` builds an undirected adjacency map. `split_grou...
[ "`build_pits` adds each endpoint to the other's neighbour set.", "`split_groups` walks each unvisited node depth-first to collect one component.", "It marks collected nodes as seen and repeats until all pits are visited.", "`reachable_pits` raises `ValueError` for an unknown entrance.", "Otherwise it scans ...
type Graph = dict[str, set[str]] def build_pits(tunnels: list[tuple[str, str]]) -> Graph: """Build an undirected adjacency map from tunnel pairs.""" graph: Graph = {} for a, b in tunnels: graph.setdefault(a, set()).add(b) graph.setdefault(b, set()).add(a) return graph def split_group...
from solution import build_pits, reachable_pits, split_groups def test_undirected_tunnels() -> None: graph = build_pits([("gate", "ledge")]) assert graph["gate"] == {"ledge"} and graph["ledge"] == {"gate"} def test_duplicate_tunnels_collapse() -> None: graph = build_pits([("gate", "ledge"), ("ledge", "g...
from solution import build_pits, reachable_pits, split_groups def test_build_pits_undirected() -> None: assert build_pits([("a", "b")]) == {"a": {"b"}, "b": {"a"}} def test_build_pits_collapses_duplicates() -> None: assert build_pits([("a", "b"), ("a", "b"), ("b", "a")]) == { "a": {"b"}, "b"...
ds-v4.1-flash
from typing import Dict, FrozenSet, List, Set Graph = Dict[str, Set[str]] def build_pits(tunnels): # type: (List[tuple[str, str]]) -> Graph graph = {} # type: Graph for i in range(len(tunnels)): a, b = tunnels[i] if a not in graph.keys(): graph[a] = set() if b not in ...
{ "mutant": "type Graph = dict[str, set[str]]\n\ndef build_pits(tunnels: list[tuple[str, str]]) -> Graph:\n \"\"\"Build an undirected adjacency map from tunnel pairs.\"\"\"\n graph: Graph = {}\n for a, b in tunnels:\n graph.setdefault(a, set()).add(b)\n graph.setdefault(b, set()).add(a)\n re...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-30e8cfda18d5206a
code
string_templates
py
class
2
short
{ "kind": "og", "text": "ashcan (A metal or plastic bin used for disposing of ashes and waste, typically located in kitchens, laboratories, or public buildings)", "sources": [ { "source": "opengloss", "id": "og-glossary:ashcan", "headword": "ashcan" } ] }
glm-5.3-flash
We label the ashcans on each lab floor with signs like "Ashcan $room — emptied by $keeper". Write a class `AshcanLabel` with `__init__(self, template_text: str) -> None`, a method `placeholders(self) -> list[str]`, and a method `render(self, fields: dict[str, str]) -> str`. `placeholders` lists the field names the temp...
[ "Compile the given text into a `string.Template` once.", "`placeholders` delegates to `Template.get_identifiers`, deduplicated in order.", "`render` calls `safe_substitute` so unknown fields remain untouched.", "Repeated identifiers all read the same entry of `fields`." ]
from string import Template class AshcanLabel: """Render waste-bin labels from a template with safe substitution.""" def __init__(self, template_text: str) -> None: self._template = Template(template_text) def placeholders(self) -> list[str]: """List the field names the template expects,...
from solution import AshcanLabel def test_missing_field_stays_literal() -> None: label = AshcanLabel("Ashcan $room — emptied by $keeper") assert label.render({"room": "B2"}) == "Ashcan B2 — emptied by $keeper" def test_all_fields_substituted() -> None: label = AshcanLabel("Ashcan $room — emptied by $kee...
from solution import AshcanLabel def test_placeholders_in_first_seen_order() -> None: label = AshcanLabel("Ashcan $room — emptied by $keeper") assert label.placeholders() == ["room", "keeper"] def test_render_fills_fields() -> None: label = AshcanLabel("Ashcan $room — emptied by $keeper") assert lab...
ds-v4.1-flash
from string import Template class AshcanLabel(object): """Render waste-bin labels from a template with safe substitution.""" def __init__(self, template_text): # type: (str) -> None self._template = Template(template_text) def placeholders(self): # type: () -> List[str] n...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { "a": [...
ol5-1ddfad9965c56a2d
code
union_find
ds
function
2
short
{ "kind": "public", "text": "lease renewal options", "sources": [] }
glm-5.3-flash
Landlord side task: we have `count` leases numbered `0..count-1`, and a list of pairs `(a, b)` meaning those two leases carry the same renewal option window, so they must be treated as one group. Write `group_options(count: int, links: list[tuple[int, int]]) -> list[list[int]]` that unions the linked leases with a unio...
[ "Initialize `parent` as each lease pointing to itself.", "`find` walks to the root while halving the path (path compression).", "For each validated link, union the two roots.", "Bucket leases by root and return the buckets sorted by first element." ]
def group_options(count: int, links: list[tuple[int, int]]) -> list[list[int]]: """Group leases that share a renewal option window.""" parent = list(range(count)) def find(x: int) -> int: while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x ...
from solution import group_options def test_linked_leases_merge() -> None: assert group_options(4, [(0, 2), (2, 3)]) == [[0, 2, 3], [1]] def test_unlinked_leases_are_singletons() -> None: assert group_options(3, []) == [[0], [1], [2]] def test_groups_sorted_by_first_element() -> None: assert group_opt...
from solution import group_options def test_singletons() -> None: assert group_options(3, []) == [[0], [1], [2]] def test_pairs() -> None: assert group_options(4, [(0, 1), (2, 3)]) == [[0, 1], [2, 3]] def test_transitive_links() -> None: assert group_options(4, [(0, 2), (2, 3)]) == [[0, 2, 3], [1]] ...
ds-v4.1-flash
from typing import Dict, List def group_options(count, links): # type: (int, List[tuple]) -> List[List[int]] parent = list(range(count)) def find(x): # type: (int) -> int while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x for pa...
{ "mutant": "def group_options(count: int, links: list[tuple[int, int]]) -> list[list[int]]:\n \"\"\"Group leases that share a renewal option window.\"\"\"\n parent = list(range(count))\n\n def find(x: int) -> int:\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = par...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-0e6ecd5895014b8f
code
operator_module
py
stateful_class
3
short
{ "kind": "og", "text": "papaws (The edible fruit produced by pawpaw trees, typically oblong and green to yellow when ripe, with custard-like flesh)", "sources": [ { "source": "opengloss", "id": "og-glossary:papaws", "headword": "papaws" } ] }
glm-5.3-flash
Help me track a crate of papaws at a farm stand. Define `Papaw` as `@dataclass(slots=True)` with fields `cultivar: str`, `weight_g: int`, `ripeness: int`, and a class `Basket` with: - `add(self, fruit: Papaw) -> None` - `discard_below(self, min_weight_g: int) -> int` - `pick_ripest(self, n: int) -> list[Papaw]` - `summ...
[ "Store fruits in a list; `add` appends.", "`discard_below` rebuilds the list, keeping fruits at or above the threshold, and returns the difference in length.", "`pick_ripest` sorts with `attrgetter(\"ripeness\", \"weight_g\")` reversed and slices.", "`summary` sorts by ripeness, groups with `groupby(attrgette...
from dataclasses import dataclass from itertools import groupby from operator import attrgetter @dataclass(slots=True) class Papaw: """One harvested papaw fruit.""" cultivar: str weight_g: int ripeness: int class Basket: """A working basket of papaws that can be culled, ranked and summarised.""...
from solution import Basket, Papaw def make(cultivar: str, weight_g: int, ripeness: int) -> Papaw: return Papaw(cultivar=cultivar, weight_g=weight_g, ripeness=ripeness) def test_discard_below_returns_and_removes() -> None: basket = Basket() basket.add(make("Sunset", 200, 2)) basket.add(make("Wabash"...
from solution import Basket, Papaw def test_empty_summary() -> None: assert Basket().summary() == "count=0 heaviest=- levels=-" def test_discard_below() -> None: basket = Basket() basket.add(Papaw("A", 100, 1)) basket.add(Papaw("B", 200, 2)) assert basket.discard_below(150) == 1 assert baske...
ds-v4.1-flash
from itertools import groupby class Papaw(object): """One harvested papaw fruit.""" def __init__(self, cultivar, weight_g, ripeness): self.cultivar = cultivar self.weight_g = weight_g self.ripeness = ripeness class Basket(object): """A working basket of papaws that can be culled...
{ "mutant": "from dataclasses import dataclass\nfrom itertools import groupby\nfrom operator import attrgetter\n\n@dataclass(slots=True)\nclass Papaw:\n \"\"\"One harvested papaw fruit.\"\"\"\n cultivar: str\n weight_g: int\n ripeness: int\n\nclass Basket:\n \"\"\"A working basket of papaws that can be...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-c01999064a8daeef
code
decimal
py
class
3
short
{ "kind": "og", "text": "ling (A large marine fish of the cod family Gadidae, Molva molva, occurring in northern Atlantic waters)", "sources": [ { "source": "opengloss", "id": "og-glossary:ling", "headword": "ling" } ] }
glm-5.3-flash
We log ling landings against a fleet quota in kilograms, and the arithmetic has to be exact. Write a class `LandingLedger` with `__init__(self, quota_kg: Decimal)`, `record(self, kg: Decimal) -> Decimal`, `remaining(self) -> Decimal` and `closed(self) -> bool`. Behaviour rules: 1. Each call to `record` rounds the lande...
[ "Store the quota and a running landed total as `Decimal` values.", "In `record`, quantize the incoming weight to 0.1 with `ROUND_DOWN`.", "Raise `ValueError` if the new total would pass the quota, before mutating state.", "Otherwise add the rounded amount and return it.", "In `remaining`, subtract and quant...
from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal _STEP = Decimal("0.1") class LandingLedger: """Track ling landings against a quota with exact decimal arithmetic.""" def __init__(self, quota_kg: Decimal) -> None: self._quota = quota_kg self._landed = Decimal(0) def record(self, kg...
from decimal import Decimal from solution import LandingLedger def test_record_rounds_down() -> None: ledger = LandingLedger(Decimal(10)) assert ledger.record(Decimal("1.27")) == Decimal("1.2") assert ledger.remaining() == Decimal("8.8") def test_record_returns_quantized() -> None: ledger = Landing...
from decimal import Decimal from solution import LandingLedger def test_round_down_to_one_decimal() -> None: ledger = LandingLedger(Decimal("10.0")) result = ledger.record(Decimal("1.19")) assert result == Decimal("1.1") assert isinstance(result, Decimal) def test_exceeds_quota_raises_and_keeps_sta...
ds-v4.1-flash
from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal _STEP = Decimal("0.1") class LandingLedger(object): """Track ling landings against a quota with exact decimal arithmetic.""" def __init__(self, quota_kg): self._quota = quota_kg self._landed = Decimal("0") def record(self, kg): ...
{ "mutant": "from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal\n_STEP = Decimal('0.1')\n\nclass LandingLedger:\n \"\"\"Track ling landings against a quota with exact decimal arithmetic.\"\"\"\n\n def __init__(self, quota_kg: Decimal) -> None:\n self._quota = quota_kg\n self._landed = Decimal(...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": true, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": []...
ol5-f81b99d2ec467290
code
simulation_step
alg
module
3
short
{ "kind": "public", "text": "campaign finance reports", "sources": [] }
glm-5.3-flash
We need a tiny simulator for matching-pool days in campaign finance reports. Write a module with the dataclass `FundState` (fields `pledged: float = 0.0`, `matched: float = 0.0`, `pool_left: float = 200.0`) and two functions. `record_pledge(state: FundState, amount: float) -> None` adds a pledge to the running total. `...
[ "`FundState` holds pledged, matched and remaining pool as a slots dataclass.", "`record_pledge` validates the cap and adds to `pledged`.", "`tick` computes the matched amount as the minimum of pledged, tick limit and pool left, then updates all three totals." ]
"""Tick a small campaign-finance matching pool.""" from dataclasses import dataclass @dataclass(slots=True) class FundState: """Running totals for one matching-pool cycle.""" pledged: float = 0.0 matched: float = 0.0 pool_left: float = 200.0 def record_pledge(state: FundState, amount: float) -> No...
from solution import FundState, record_pledge, tick def test_pledge_accumulates() -> None: state = FundState() record_pledge(state, 30.0) record_pledge(state, 20.0) assert state.pledged == 50.0 def test_oversized_pledge_raises() -> None: state = FundState() try: record_pledge(state, ...
from solution import FundState, record_pledge, tick def test_record_pledge_adds_to_running_total() -> None: state = FundState() record_pledge(state, 100.0) record_pledge(state, 250.5) assert state.pledged == 350.5 def test_record_pledge_allows_exactly_five_hundred() -> None: state = FundState() ...
ds-v4.1-flash
"""Tick a small campaign-finance matching pool.""" class FundState(object): """Running totals for one matching-pool cycle.""" def __init__(self, pledged=0.0, matched=0.0, pool_left=200.0): # type: (float, float, float) -> None self.pledged = pledged self.matched = matched self...
{ "mutant": "\"\"\"Tick a small campaign-finance matching pool.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass FundState:\n \"\"\"Running totals for one matching-pool cycle.\"\"\"\n pledged: float = 0.0\n matched: float = 0.0\n pool_left: float = 200.0\n\ndef record_pledge(state...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-df4ccc50133c2d94
code
dp_lcs
alg
class
2
short
{ "kind": "public", "text": "board meeting minutes", "sources": [] }
ds-v4.1-flash
Our board meeting minutes get rewound and rewritten, and the chair wants to know which lines survived the edit. Build a class `MinutesMatcher(before: list[str], after: list[str])` with the methods `kept() -> list[str]`, `dropped() -> list[str]` and `summary() -> str`. `kept` returns the longest common subsequence of th...
[ "Fill an `(n+1) x (m+1)` table of longest common subsequence lengths from the end.", "Walk the two lists forward with two indices, pushing the table when the current lines differ.", "Collect taken lines for `kept` and skipped earlier lines for `dropped` in the same walk.", "Format the counts in `summary`." ]
"""Compare two revisions of board meeting minutes with dynamic programming.""" def _lcs_table(before: list[str], after: list[str]) -> list[list[int]]: table = [[0] * (len(after) + 1) for _ in range(len(before) + 1)] for i in range(len(before) - 1, -1, -1): for j in range(len(after) - 1, -1, -1): ...
from solution import MinutesMatcher EARLIER = ["roll call", "budget", "harbour lease", "any other business"] LATER = ["roll call", "harbour lease", "new chairs"] def test_kept_lines_in_order() -> None: assert MinutesMatcher(EARLIER, LATER).kept() == ["roll call", "harbour lease"] def test_dropped_lines_keep_or...
from solution import MinutesMatcher def test_kept_is_lcs() -> None: m = MinutesMatcher(["a", "b", "c"], ["a", "c"]) assert m.kept() == ["a", "c"] def test_repeated_lines_match_one_for_one() -> None: m = MinutesMatcher(["x", "x", "x"], ["x", "x"]) assert m.kept() == ["x", "x"] assert m.dropped() ...
glm-5.3-flash
"""Compare two revisions of board meeting minutes with dynamic programming.""" from typing import List def _lcs_table(before: List[str], after: List[str]) -> List[List[int]]: table = [] # type: List[List[int]] for _ in range(len(before) + 1): table.append([0] * (len(after) + 1)) i = len(before) ...
{ "mutant": "\"\"\"Compare two revisions of board meeting minutes with dynamic programming.\"\"\"\n\ndef _lcs_table(before: list[str], after: list[str]) -> list[list[int]]:\n table = [[0] * (len(after) + 1) for _ in range(len(before) + 1)]\n for i in range(len(before) - 1, -1, -1):\n for j in range(len(a...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-49eba59134396e31
code
match_sequences
py
module
3
short
{ "kind": "og", "text": "ringside (The zone immediately surrounding a boxing ring, particularly the seating closest to the action)", "sources": [ { "source": "opengloss", "id": "og-glossary:ringside", "headword": "ringside" } ] }
ds-v4.1-flash
We keep the seat plan for the ringside rows in a small module. Write `describe_row(seats: list[str]) -> str`, `split_ends(seats: list[str]) -> tuple[str | None, list[str], str | None]` and `first_non_aisle(seats: list[str | None]) -> str | None`. A row is a flat list of seat labels; `first_non_aisle` also accepts `None...
[ "`describe_row` matches the list against `[]`, `[only]`, `[left, right]` and `[first, *middle, last]`.", "The two-seat case comes before the star case, so pairs never reach the span branch.", "`split_ends` matches the same shapes and returns fixed triples.", "`first_non_aisle` skips a leading `None` by recurs...
"""Seat rows for the ringside of a small boxing venue.""" def describe_row(seats: list[str]) -> str: """Describe a ringside row by its length and end seats.""" match seats: case []: return "empty" case [only]: return f"single:{only}" case [left, right]: ...
from solution import describe_row, first_non_aisle, split_ends def test_empty_row() -> None: assert describe_row([]) == "empty" assert split_ends([]) == (None, [], None) assert first_non_aisle([]) is None def test_single_seat() -> None: assert describe_row(["A1"]) == "single:A1" assert split_end...
from solution import describe_row, first_non_aisle, split_ends def test_describe_empty() -> None: assert describe_row([]) == "empty" def test_describe_single() -> None: assert describe_row(["A1"]) == "single:A1" def test_describe_pair() -> None: assert describe_row(["A1", "A2"]) == "pair:A1>A2" def ...
glm-5.3-flash
"""Seat rows for the ringside of a small boxing venue.""" from typing import List, Optional, Tuple def describe_row(seats: List[str]) -> str: """Describe a ringside row by its length and end seats.""" if not seats: return "empty" if len(seats) == 1: return "single:%s" % seats[0] if len...
{ "mutant": "\"\"\"Seat rows for the ringside of a small boxing venue.\"\"\"\n\ndef describe_row(seats: list[str]) -> str:\n \"\"\"Describe a ringside row by its length and end seats.\"\"\"\n match seats:\n case []:\n return 'empty'\n case [only]:\n return f'single:{only}'\n ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining"...
ol5-97f9ec2b09478fe4
code
base_conversion
alg
enum_plus_fn
2
short
{ "kind": "topic", "text": "signal processing technique (a topic in technology)", "sources": [ { "source": "opengloss", "id": "og-enc:signal processing technique", "headword": "signal processing technique" } ] }
ds-v4.1-flash
Our serial link writes packet words in a chosen line-code base, and the base is currently picked by hand. Write an `IntEnum` called `Base` with members `BINARY = 2`, `OCTAL = 8` and `HEX = 16`, and a function `to_base(value: int, *, base: Base) -> str` that writes a non-negative integer in that base and dispatches on t...
[ "`to_base` rejects a negative value before doing any work.", "It matches on the enum member and picks the digit alphabet for that base.", "A helper repeatedly divides by the alphabet length, collecting digits.", "The collected digits are joined in reverse to give the written word." ]
from enum import IntEnum DIGITS = "0123456789ABCDEF" class Base(IntEnum): """Line-code base used when a packet word is written out.""" BINARY = 2 OCTAL = 8 HEX = 16 def _encode(value: int, alphabet: str) -> str: if value == 0: return alphabet[0] digits: list[str] = [] current =...
from solution import Base, to_base def test_zero_is_the_same_in_every_base() -> None: assert to_base(0, base=Base.BINARY) == "0" assert to_base(0, base=Base.OCTAL) == "0" assert to_base(0, base=Base.HEX) == "0" def test_hex_digits_use_uppercase_letters() -> None: assert to_base(255, base=Base.HEX) =...
from solution import Base, to_base def test_enum_members() -> None: assert Base.BINARY == 2 assert Base.OCTAL == 8 assert Base.HEX == 16 def test_zero() -> None: assert to_base(0, base=Base.BINARY) == "0" assert to_base(0, base=Base.OCTAL) == "0" assert to_base(0, base=Base.HEX) == "0" def...
glm-5.3-flash
from typing import List DIGITS = "0123456789ABCDEF" class Base: BINARY = 2 OCTAL = 8 HEX = 16 def _encode(value: int, alphabet: str) -> str: if value == 0: return alphabet[0] digits: List[str] = [] current = value while current > 0: current, remainder = divmod(current, l...
{ "mutant": "from enum import IntEnum\nDIGITS = '0123456789ABCDEF'\n\nclass Base(IntEnum):\n \"\"\"Line-code base used when a packet word is written out.\"\"\"\n BINARY = 2\n OCTAL = 8\n HEX = 16\n\ndef _encode(value: int, alphabet: str) -> str:\n if value == 1:\n return alphabet[0]\n digits:...
{ "tests_teacher": [ "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-ab873569ddac3e01
code
majority_vote
alg
generator
2
short
{ "kind": "og", "text": "fore (The forward part of a ship or other object)", "sources": [ { "source": "opengloss", "id": "og-glossary:fore", "headword": "fore" } ] }
ds-v4.1-flash
We count labels painted on the forward part of a ship. Write a generator `fore_marks(entries: Iterable[str]) -> Iterator[str]` that yields each entry with surrounding whitespace stripped, skipping entries that are blank after stripping, and write `majority_fore(entries: Iterable[str]) -> str | None` that consumes that ...
[ "`fore_marks` strips each entry and yields it when non-empty.", "`majority_fore` keeps a candidate and a counter, updating it with the vote rule.", "Keep the marks in a list while voting so the candidate can be verified.", "Return the candidate only when its true tally is more than half the marks, else `None`...
from collections.abc import Iterable, Iterator def fore_marks(entries: Iterable[str]) -> Iterator[str]: """Yield each non-blank entry with surrounding whitespace removed.""" for entry in entries: mark = entry.strip() if mark: yield mark def majority_fore(entries: Iterable[str]) -...
from solution import fore_marks, majority_fore def test_marks_skip_blanks_and_strip() -> None: assert list(fore_marks([" port ", "", " ", "bow"])) == ["port", "bow"] def test_majority_returns_clear_winner() -> None: assert majority_fore(["bow", "bow", "stern", "bow"]) == "bow" def test_exact_half_is_not...
from collections.abc import Iterator from solution import fore_marks, majority_fore def as_list(it: Iterator[str]) -> list[str]: return list(it) def test_fore_marks_strips_and_skips_blanks() -> None: assert as_list(fore_marks([" a ", "b", " ", "\tc\t", ""])) == ["a", "b", "c"] def test_fore_marks_empty_...
glm-5.3-flash
from typing import Iterable, Iterator, List, Optional def fore_marks(entries: Iterable[str]) -> Iterator[str]: """Yield each non-blank entry with surrounding whitespace removed.""" for entry in entries: mark = entry.strip() if mark: yield mark def majority_fore(entries: Iterable[...
{ "mutant": "from collections.abc import Iterable, Iterator\n\ndef fore_marks(entries: Iterable[str]) -> Iterator[str]:\n \"\"\"Yield each non-blank entry with surrounding whitespace removed.\"\"\"\n for entry in entries:\n mark = entry.strip()\n if mark:\n yield mark\n\ndef majority_fo...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_...
ol5-ea05dddb83ab9f06
code
string_matching
alg
module
4
short
{ "kind": "og", "text": "warble (A melodic wavering sound produced by a bird)", "sources": [ { "source": "opengloss", "id": "og-glossary:warble", "headword": "warble" } ] }
glm-5.3-flash
I log birdsong transcripts and want to detect a warble motif even when it overlaps itself. Write a module with `find_motifs(text: str, motif: str) -> list[int]` returning the start indices of every occurrence of `motif` in `text`, including overlapping ones, in ascending order, and `count_motifs(text: str, motif: str) ...
[ "Validate the motif is non-empty in `find_motifs` first.", "Use `str.find` starting at position 0 to locate the first match.", "Loop, recording each index and resuming the search at `index + 1` so overlaps are found.", "Implement `count_motifs` as the length of `find_motifs`'s result." ]
"""Counting overlapping warble motifs in birdsong transcripts.""" def find_motifs(text: str, motif: str) -> list[int]: """Return the start indices of all overlapping matches of motif.""" if not motif: msg = "motif must not be empty" raise ValueError(msg) starts: list[int] = [] at = tex...
from solution import count_motifs, find_motifs def test_overlapping_matches_found() -> None: assert find_motifs("aaaa", "aa") == [0, 1, 2] def test_overlap_in_warble_call() -> None: assert find_motifs("wawawa", "awa") == [1, 3] def test_empty_motif_raises_in_find() -> None: try: find_motifs("c...
from solution import count_motifs, find_motifs def test_overlapping_matches() -> None: assert find_motifs("aaaa", "aa") == [0, 1, 2] assert count_motifs("aaaa", "aa") == 3 def test_ascending_indices_and_count_agree() -> None: text = "ababab" assert find_motifs(text, "ab") == [0, 2, 4] assert cou...
ds-v4.1-flash
"""Counting overlapping warble motifs in birdsong transcripts.""" def find_motifs(text, motif): """Return the start indices of all overlapping matches of motif.""" if len(motif) == 0: raise ValueError("motif must not be empty") starts = [] at = text.find(motif, 0) while at != -1: s...
{ "mutant": "\"\"\"Counting overlapping warble motifs in birdsong transcripts.\"\"\"\n\ndef find_motifs(text: str, motif: str) -> list[int]:\n \"\"\"Return the start indices of all overlapping matches of motif.\"\"\"\n if not motif:\n msg = 'motif must not be empty'\n raise ValueError(msg)\n st...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_...
ol5-cfb8d5e065d6ef26
code
hashable_value
py
stateful_class
4
short
{ "kind": "og", "text": "turtleneck (A close-fitting knitted garment with a high neck that extends to cover the neck, typically worn as outerwear or knitwear)", "sources": [ { "source": "opengloss", "id": "og-glossary:turtleneck", "headword": "turtleneck" } ] }
glm-5.3-flash
I want a small inventory for turtlenecks. Write a frozen dataclass `Turtleneck` with fields `colour: str`, `size: str`, `wool: bool`, and a class `Wardrobe` with `__init__(self) -> None`, `add(self, item: Turtleneck) -> None`, `remove(self, item: Turtleneck) -> None`, `total(self) -> int` and `summary(self) -> list[tup...
[ "Use a frozen dataclass so items are hashable and compare by fields.", "Keep a `dict[Turtleneck, int]` of counts in the wardrobe.", "`add` increments the count for the key; `remove` decrements and deletes the key at zero.", "`remove` raises ValueError when the key is absent or its count is zero.", "`summary...
"""A turtleneck inventory keyed by immutable garment descriptions.""" from dataclasses import dataclass @dataclass(frozen=True) class Turtleneck: """An immutable turtleneck description, usable as a dict or set member.""" colour: str size: str wool: bool class Wardrobe: """Counts turtlenecks gr...
from solution import Turtleneck, Wardrobe def test_equal_items_share_one_key() -> None: w = Wardrobe() w.add(Turtleneck("grey", "m", True)) w.add(Turtleneck("grey", "m", True)) assert w.summary() == [(Turtleneck("grey", "m", True), 2)] assert w.total() == 2 def test_remove_missing_raises() -> No...
from solution import Turtleneck, Wardrobe def _key() -> Turtleneck: return Turtleneck(colour="blue", size="M", wool=True) def test_equal_items_are_one_kind() -> None: w = Wardrobe() w.add(_key()) w.add(Turtleneck(colour="blue", size="M", wool=True)) assert w.total() == 2 assert len(w.summary...
ds-v4.1-flash
"""A turtleneck inventory keyed by immutable garment descriptions.""" class Turtleneck(object): """An immutable turtleneck description, usable as a dict or set member.""" __slots__ = ("colour", "size", "wool") def __init__(self, colour, size, wool): self.colour = colour self.size = size ...
{ "mutant": "\"\"\"A turtleneck inventory keyed by immutable garment descriptions.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Turtleneck:\n \"\"\"An immutable turtleneck description, usable as a dict or set member.\"\"\"\n colour: str\n size: str\n wool: bool\n\nclass Wardr...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-c854d813050c66b5
code
heap_merge
ds
stateful_class
6
short
{ "kind": "og", "text": "charcoal (A porous, carbon-rich material made by heating organic matter in limited oxygen, used as a fuel, reducing agent, and filtration medium)", "sources": [ { "source": "opengloss", "id": "og-glossary:charcoal", "headword": "charcoal" } ] }
glm-5.3-flash
We burn charcoal in numbered kilns and each kiln writes its core temperature readings as an already-sorted list. Please write a module with one class, `KilnLog`, holding batches of sorted readings. Signatures: `KilnLog.__init__(self) -> None`, `KilnLog.add_batch(self, readings: Iterable[int]) -> None`, `KilnLog.all_rea...
[ "Store accepted batches in a list of lists.", "On `add_batch`, materialise the batch and check pairwise nondecreasing order before storing.", "`all_readings` yields from `heapq.merge` over the stored batches, which is lazy.", "`summary` drains the merged stream once and reports counts and the peak." ]
"""Merge sorted kiln temperature batches into one ordered readings stream.""" import heapq from collections.abc import Iterable, Iterator from itertools import pairwise class KilnLog: """Holds sorted kiln temperature batches and merges them lazily.""" def __init__(self) -> None: self._batches: list[...
from solution import KilnLog def test_merged_order() -> None: log = KilnLog() log.add_batch([220, 480, 510]) log.add_batch([200, 470, 470, 600]) assert list(log.all_readings()) == [200, 220, 470, 470, 480, 510, 600] def test_duplicates_kept() -> None: log = KilnLog() log.add_batch([300, 300]...
from solution import KilnLog def test_merge_is_non_decreasing() -> None: log = KilnLog() log.add_batch([1, 4, 7]) log.add_batch([2, 3, 9]) assert list(log.all_readings()) == [1, 2, 3, 4, 7, 9] def test_equal_readings_are_kept() -> None: log = KilnLog() log.add_batch([1, 1, 2]) log.add_ba...
ds-v4.1-flash
"""Merge sorted kiln temperature batches into one ordered readings stream.""" import heapq from typing import Dict, Iterable, Iterator, List, Optional class KilnLog(object): """Holds sorted kiln temperature batches and merges them lazily.""" def __init__(self): # type: () -> None self._batch...
{ "mutant": "\"\"\"Merge sorted kiln temperature batches into one ordered readings stream.\"\"\"\nimport heapq\nfrom collections.abc import Iterable, Iterator\nfrom itertools import pairwise\n\nclass KilnLog:\n \"\"\"Holds sorted kiln temperature batches and merges them lazily.\"\"\"\n\n def __init__(self) -> N...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining...
ol5-2b5207bf01647927
code
boundary_values
test
stateful_class
2
short
{ "kind": "og", "text": "tanekaha (A common name for the western red cedar, a large evergreen conifer native to the Pacific Northwest, recognized scientifically as Thuja...)", "sources": [ { "source": "opengloss", "id": "og-glossary:tanekaha", "headword": "tanekaha" } ] }
glm-5.3-flash
Our cedar mill (western red cedar, Thuja plicata — we log it under the trade name "tanekaha" in the yard software) grades green boards by thickness. Write a class `BoardYard` with `BoardYard.__init__(self) -> None`, `BoardYard.add(self, thickness_mm: int) -> None` and `BoardYard.summary(self) -> dict[str, int | None]`....
[ "Keep accepted thicknesses in a list.", "Validate against the inclusive band and reject the just-outside values.", "`summary` reports the count and min and max, with `None`s when empty." ]
"""Track cedar board thicknesses within an inclusive mill tolerance.""" class BoardYard: """Accepts board thicknesses in millimetres within 15..50 inclusive.""" MIN_MM = 15 MAX_MM = 50 def __init__(self) -> None: self._boards: list[int] = [] def add(self, thickness_mm: int) -> None: ...
from solution import BoardYard def test_below_boundary_rejected() -> None: yard = BoardYard() try: yard.add(14) except ValueError: pass else: raise AssertionError("expected ValueError") assert yard.summary() == {"boards": 0, "min": None, "max": None} def test_above_bounda...
from solution import BoardYard def test_empty_summary() -> None: yard = BoardYard() assert yard.summary() == {"boards": 0, "min": None, "max": None} def test_accepts_lower_boundary() -> None: yard = BoardYard() yard.add(15) assert yard.summary() == {"boards": 1, "min": 15, "max": 15} def test_...
ds-v4.1-flash
"""Track cedar board thicknesses within an inclusive mill tolerance.""" class BoardYard(object): """Accepts board thicknesses in millimetres within 15..50 inclusive.""" MIN_MM = 15 MAX_MM = 50 def __init__(self): # type: () -> None self._boards = [] # type: List[int] def add(se...
{ "mutant": "\"\"\"Track cedar board thicknesses within an inclusive mill tolerance.\"\"\"\n\nclass BoardYard:\n \"\"\"Accepts board thicknesses in millimetres within 15..50 inclusive.\"\"\"\n MIN_MM = 15\n MAX_MM = 50\n\n def __init__(self) -> None:\n self._boards: list[int] = []\n\n def add(se...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-07dd035d8d56adb9
code
dedupe_order
alg
generator
6
short
{ "kind": "legal", "text": "Disclosure of record to person other than the individual to whom it pertains (the subject of 15 CFR 4.30, Commerce and Foreign Trade)", "sources": [ { "source": "ecfr", "id": "15 CFR 4.30" } ] }
glm-5.3-flash
Under the disclosure-of-record rules we care about, each disclosure event is logged as one line of text shaped like `"REC-004 alice"` — a record id, one space, then a recipient. Write a module with a generator `unique_recipients(lines: Iterable[str]) -> Iterator[str]` and a consumer `recipient_counts(lines: Iterable[st...
[ "Share a small parse helper that strips the line, skips blanks, and splits on the first space.", "The generator keeps a seen set and yields a recipient the first time it appears.", "The consumer tallies every occurrence in a dict of totals.", "The consumer re-derives first-seen order with `dict.fromkeys` over...
"""Track record disclosures to recipients, deduplicated in first-seen order.""" from collections.abc import Iterable, Iterator def _parse(line: str) -> tuple[str, str]: """Split one log line into a record id and a recipient.""" stripped = line.strip() if not stripped: return "", "" record, _,...
from solution import recipient_counts, unique_recipients def test_first_seen_order_no_repeats() -> None: lines = ["R1 alice", "R2 bob", "R3 alice"] assert list(unique_recipients(lines)) == ["alice", "bob"] def test_blank_lines_skipped() -> None: lines = ["", " ", "R1 carol", ""] assert list(unique...
from solution import recipient_counts, unique_recipients def test_unique_recipients_first_seen_order() -> None: lines = ["REC-1 alice", "REC-2 bob", "REC-3 alice"] assert list(unique_recipients(lines)) == ["alice", "bob"] def test_unique_recipients_skips_blank_lines() -> None: lines = ["", " ", "REC-1...
ds-v4.1-flash
"""Track record disclosures to recipients, deduplicated in first-seen order.""" def _parse(line): # type: (str) -> Tuple[str, str] """Split one log line into a record id and a recipient.""" stripped = line.strip() if not stripped: return "", "" parts = stripped.split(" ", 1) record = p...
{ "mutant": "\"\"\"Track record disclosures to recipients, deduplicated in first-seen order.\"\"\"\nfrom collections.abc import Iterable, Iterator\n\ndef _parse(line: str) -> tuple[str, str]:\n \"\"\"Split one log line into a record id and a recipient.\"\"\"\n stripped = line.strip()\n if not stripped:\n ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b...
ol5-440d07d8c182f59f
code
bucket_sort
alg
generator
3
short
{ "kind": "legal", "text": "How does a lessee pay the Bureau-operated school under a lease? (the subject of 25 CFR 48.111, Indians)", "sources": [ { "source": "ecfr", "id": "25 CFR 48.111", "agency": "BUREAU OF INDIAN AFFAIRS, DEPARTMENT OF THE INTERIOR" } ] }
glm-5.3-flash
For a Bureau-operated school's lease ledger I need a small payment scheduler. Write `payment_buckets(payments: list[LeasePayment], months: int = 12) -> Iterator[MonthBucket]` where `LeasePayment` is a `tuple[int, float]` of (month, amount) and `MonthBucket` is a slots dataclass with `month: int` and `payments: list[Lea...
[ "Validate `months >= 1` up front and raise `ValueError`.", "Build an empty list per month, then append each payment after checking its month range.", "Yield a `MonthBucket` per month in ascending month order; append order preserves stability.", "`payment_report` iterates the generator and skips empty buckets,...
"""Bucket lease payments by calendar month and summarise them.""" from collections.abc import Iterator from dataclasses import dataclass type LeasePayment = tuple[int, float] @dataclass(slots=True) class MonthBucket: """One month's lease payments with their count and total.""" month: int payments: list...
from solution import LeasePayment, payment_buckets, payment_report def test_buckets_yielded_in_month_order() -> None: payments: list[LeasePayment] = [(3, 50.0), (1, 20.0), (3, 10.0)] buckets = list(payment_buckets(payments, months=3)) assert [b.month for b in buckets] == [1, 2, 3] assert buckets[0].pa...
from solution import MonthBucket, payment_buckets, payment_report def test_invalid_months_raises_before_yielding() -> None: try: gen = payment_buckets([], 0) next(gen) except ValueError: pass else: raise AssertionError("expected ValueError") def test_out_of_range_payment_...
ds-v4.1-flash
null
{ "mutant": "\"\"\"Bucket lease payments by calendar month and summarise them.\"\"\"\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\ntype LeasePayment = tuple[int, float]\n\n@dataclass(slots=True)\nclass MonthBucket:\n \"\"\"One month's lease payments with their count and total.\"\"\"\n ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-e77f4e63aaa2d341
code
input_validation
test
pure_pipeline
4
short
{ "kind": "public", "text": "weather station logs", "sources": [] }
glm-5.3-flash
We archive weather-station log lines like `"hillsite 7.5"`. Write three functions. `parse_line(line: str) -> tuple[str, float]` splits a line into a station name and a temperature and returns them. `daily_peaks(lines: list[str]) -> dict[str, float]` is the pipeline: it cleans, parses, and keeps the highest temperature ...
[ "Check every entry is a `str` and raise `TypeError` otherwise.", "Skip entries that are blank after stripping.", "`parse_line` splits on whitespace, requires exactly two parts, and converts the second with `float`, raising `ValueError` on failure.", "The pipeline fills a dict, keeping the first value when tem...
def parse_line(line: str) -> tuple[str, float]: """Split one log line into a station name and a temperature.""" parts = line.split() if len(parts) != 2: raise ValueError("malformed log line") try: temperature = float(parts[1]) except ValueError as error: raise ValueError("mal...
from solution import daily_peaks, parse_line def test_parse_line_basic() -> None: assert parse_line("hillsite 7.5") == ("hillsite", 7.5) def test_parse_line_rejects_shape() -> None: try: parse_line("hillsite") except ValueError: pass else: raise AssertionError("expected Value...
import math from typing import cast from solution import daily_peaks, parse_line def test_parse_line_valid() -> None: assert parse_line("hillsite 7.5") == ("hillsite", 7.5) def test_parse_line_rejects_malformed() -> None: for line in ("hillsite", "hillsite 7.5 extra", "hillsite warm"): try: ...
ds-v4.1-flash
def parse_line(line): """Split one log line into a station name and a temperature.""" parts = line.split() if len(parts) != 2: raise ValueError("malformed log line") try: temperature = float(parts[1]) except ValueError as error: raise ValueError("malformed log line") from err...
{ "mutant": "def parse_line(line: str) -> tuple[str, float]:\n \"\"\"Split one log line into a station name and a temperature.\"\"\"\n parts = line.split()\n if len(parts) != 2:\n raise ValueError('malformed log line')\n try:\n temperature = float(parts[1])\n except ValueError as error:\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining"...
ol5-5a2b86e1b42f47ee
code
diff_lists
alg
dataclass_plus_fn
4
short
{ "kind": "og", "text": "stylopodium (an enlargement at the base of the style in some Umbelliferae)", "sources": [ { "source": "opengloss", "id": "og-glossary:stylopodium", "headword": "stylopodium" } ] }
glm-5.3-flash
For a botany note-taking tool I need a snapshot differ for stylopodium measurements. Write `@dataclass(slots=True)` class `StyloRecord` with fields `specimen: str` and `width_mm: float`, and a function `diff_snapshots(old: list[StyloRecord], new: list[StyloRecord]) -> dict[str, list[str]]` that returns a dict with keys...
[ "Validate uniqueness of specimen keys in both lists.", "Build key-to-record dicts preserving order.", "Compute added, removed and changed from the two dicts.", "Format changed entries with an f-string using `:g`." ]
from dataclasses import dataclass @dataclass(slots=True) class StyloRecord: """One stylopodium width measurement for a specimen.""" specimen: str width_mm: float def _unique(records: list[StyloRecord]) -> dict[str, float]: seen: dict[str, float] = {} for rec in records: if rec.specimen ...
from solution import StyloRecord, diff_snapshots def rec(name: str, w: float) -> StyloRecord: return StyloRecord(specimen=name, width_mm=w) def test_added_and_removed() -> None: old = [rec("a", 1.0)] new = [rec("b", 2.0)] assert diff_snapshots(old, new) == { "added": ["b"], "removed"...
from solution import StyloRecord, diff_snapshots def test_empty_snapshots() -> None: assert diff_snapshots([], []) == {"added": [], "removed": [], "changed": []} def test_added_and_removed_follow_input_order() -> None: old = [StyloRecord("b", 1.0), StyloRecord("a", 1.0)] new = [StyloRecord("d", 1.0), St...
ds-v4.1-flash
class StyloRecord(object): """One stylopodium width measurement for a specimen.""" __slots__ = ("specimen", "width_mm") def __init__(self, specimen, width_mm): self.specimen = specimen self.width_mm = width_mm def __eq__(self, other): return (isinstance(other, StyloRecord) ...
{ "mutant": "from dataclasses import dataclass\n\n@dataclass(slots=True)\nclass StyloRecord:\n \"\"\"One stylopodium width measurement for a specimen.\"\"\"\n specimen: str\n width_mm: float\n\ndef _unique(records: list[StyloRecord]) -> dict[str, float]:\n seen: dict[str, float] = {}\n for rec in recor...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": true, "btests_changed": false, "remaining": [], "b_remaining"...
ol5-c092e3eaf620ebf7
code
string_matching
alg
module
6
short
{ "kind": "legal", "text": "Time for processing appeals involving allegations of discrimination (the subject of 5 CFR 1201.156, Administrative Personnel)", "sources": [ { "source": "ecfr", "id": "5 CFR 1201.156", "agency": "MERIT SYSTEMS PROTECTION BOARD" } ] }
glm-5.3-flash
Appeals filed with our personnel board must state a processing deadline, and I want to scan case memos for the phrases we use. Write a module with two functions. `find_all(text: str, needle: str) -> list[int]` returns the start indexes of all overlapping occurrences of `needle` in `text` in ascending order. `deadline_d...
[ "In `find_all`, loop with `str.find(text, needle, start)` advancing `start` to `pos + 1` so overlaps are found.", "Validate that the needle is non-empty before scanning.", "Collect ascending start indexes until `find` returns -1.", "In `deadline_days`, locate the first `\"within \"`, then the next `\" days\"`...
"""Scanning appeal memos for overlapping phrases and processing deadlines.""" def find_all(text: str, needle: str) -> list[int]: """Return ascending start indexes of all overlapping occurrences of needle.""" if not needle: raise ValueError("needle must not be empty") positions: list[int] = [] ...
from solution import deadline_days, find_all def test_overlapping_matches() -> None: assert find_all("aaa", "aa") == [0, 1] def test_empty_needle_raises() -> None: try: find_all("abc", "") except ValueError: pass else: raise AssertionError("expected ValueError") def test_ne...
from solution import deadline_days, find_all def test_find_all_counts_overlapping_matches() -> None: assert find_all("aaa", "aa") == [0, 1] def test_find_all_empty_needle_raises() -> None: try: find_all("abc", "") except ValueError: pass else: raise AssertionError("expected V...
ds-v4.1-flash
"""Scanning appeal memos for overlapping phrases and processing deadlines.""" def find_all(text, needle): """Return ascending start indexes of all overlapping occurrences of needle.""" if not needle: raise ValueError("needle must not be empty") positions = [] start = 0 while True: ...
{ "mutant": "\"\"\"Scanning appeal memos for overlapping phrases and processing deadlines.\"\"\"\n\ndef find_all(text: str, needle: str) -> list[int]:\n \"\"\"Return ascending start indexes of all overlapping occurrences of needle.\"\"\"\n if not needle:\n raise ValueError('needle must not be empty')\n ...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": fals...
ol5-b72016860cfc6ba1
code
ring_buffer
ds
module
3
short
{ "kind": "og", "text": "duckbills (The broad flattened beak of ducks and related waterfowl, adapted for surface feeding and filter-feeding)", "sources": [ { "source": "opengloss", "id": "og-glossary:duckbills", "headword": "duckbills" } ] }
glm-5.3-flash
For a waterfowl feeding study I need a tiny sampling module. Write a class `FeedRing` with `__init__(self, capacity: int)` that raises `ValueError` when `capacity < 1`, a method `push(self, size: float) -> bool`, and a method `samples(self) -> list[float]`; plus two functions `record_bite(ring: FeedRing, size: float) -...
[ "Store sizes in a fixed list with a `head` index that wraps with modulo.", "Track how many slots are filled to know the ring order and the displaced flag.", "`samples` reconstructs oldest-to-newest order from `head` and the fill count.", "`median_size` sorts the samples and picks the middle, averaging two for...
class FeedRing: """A fixed-capacity ring of plankton sizes in millimetres; the oldest entry is overwritten first.""" def __init__(self, capacity: int) -> None: """Create an empty ring with the given positive capacity.""" if capacity < 1: raise ValueError("capacity must be at least 1...
from solution import FeedRing, median_size, record_bite def test_push_returns_false_until_full() -> None: ring = FeedRing(3) assert record_bite(ring, 1.0) is False assert record_bite(ring, 2.0) is False assert record_bite(ring, 3.0) is False assert record_bite(ring, 4.0) is True def test_overwri...
from solution import FeedRing, median_size, record_bite def test_capacity_below_one_raises() -> None: for capacity in (0, -1): try: FeedRing(capacity) except ValueError: pass else: raise AssertionError("expected ValueError") def test_push_returns_false...
ds-v4.1-flash
from typing import List, Optional class FeedRing(object): """A fixed-capacity ring of plankton sizes in millimetres; the oldest entry is overwritten first.""" def __init__(self, capacity): if capacity < 1: raise ValueError("capacity must be at least 1") self._data = [None] * capac...
{ "mutant": "class FeedRing:\n \"\"\"A fixed-capacity ring of plankton sizes in millimetres; the oldest entry is overwritten first.\"\"\"\n\n def __init__(self, capacity: int) -> None:\n \"\"\"Create an empty ring with the given positive capacity.\"\"\"\n if capacity < 1:\n raise ValueE...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": ...
ol5-4141d470426c209e
code
generator
py
protocol_impl
5
short
{ "kind": "og", "text": "hogchoker (A small, bottom-dwelling flatfish, Trinectes maculatus, found in shallow brackish waters along the Atlantic coast of North America)", "sources": [ { "source": "opengloss", "id": "og-glossary:hogchoker", "headword": "hogchoker" } ] }
glm-5.3-flash
I am surveying hogchoker stations in a brackish creek and want a lazy filter over salinity readings. Define a `Protocol` named `SalinityGauge` with a single method `reading(self) -> float`, two classes that satisfy it — `FixedGauge(value: float)`, which always returns `value`, and `SweepGauge(values: list[float])`, whi...
[ "Define the `SalinityGauge` protocol with one `reading` method.", "`FixedGauge` stores one value; `SweepGauge` walks an index and clamps it at the last value.", "`tolerable_stations` loops over sites, reads the gauge once per site, and yields the name when the reading is in range.", "Being a generator, it doe...
from collections.abc import Iterator from typing import Protocol class SalinityGauge(Protocol): """Anything that can produce a salinity reading in practical salinity units.""" def reading(self) -> float: ... class FixedGauge: """A gauge pinned to one constant salinity.""" def __init__(self, value:...
from collections.abc import Iterator from solution import FixedGauge, SalinityGauge, SweepGauge, tolerable_stations class CountingGauge: """Test gauge that records how many readings were taken.""" def __init__(self, values: list[float]) -> None: self.values = values self.calls = 0 def r...
from solution import FixedGauge, SweepGauge, tolerable_stations def test_fixed_gauge_always_returns_value() -> None: gauge = FixedGauge(3.5) assert gauge.reading() == 3.5 assert gauge.reading() == 3.5 def test_sweep_gauge_order_and_hold() -> None: gauge = SweepGauge([1.0, 2.0]) assert gauge.read...
ds-v4.1-flash
from typing import Iterator, List, Protocol class SalinityGauge(Protocol): """Anything that can produce a salinity reading in practical salinity units.""" def reading(self): # type: () -> float ... class FixedGauge(object): """A gauge pinned to one constant salinity.""" def __init__(self,...
{ "mutant": "from collections.abc import Iterator\nfrom typing import Protocol\n\nclass SalinityGauge(Protocol):\n \"\"\"Anything that can produce a salinity reading in practical salinity units.\"\"\"\n\n def reading(self) -> float:\n ...\n\nclass FixedGauge:\n \"\"\"A gauge pinned to one constant sal...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...
ol5-578dd68caf552896
code
sliding_window
alg
validator
4
short
{ "kind": "legal", "text": "Reporting and recordkeeping requirements (the subject of 40 CFR 63.311, Protection of Environment)", "sources": [ { "source": "ecfr", "id": "40 CFR 63.311", "agency": "ENVIRONMENTAL PROTECTION AGENCY" } ] }
glm-5.3-flash
For our quarterly emissions file we need a validator that checks a rolling window of readings before the report can be filed. Write `def validate_readings(values: list[float], *, window: int = 7, max_avg: float = 12.0, max_gap_days: int = 1) -> list[str]` where each value is a daily emission level and consecutive entri...
[ "Validate `window >= 1`, else `ValueError`.", "If `len(values) < window`, return `[\"too few readings\"]`.", "Sum the first window, then slide: subtract the leaving value, add the entering value.", "For each window start whose average exceeds `max_avg`, append the formatted message with 1-based day numbers." ...
"""Rolling-window checks on daily emission readings before filing.""" from collections.abc import Sequence def validate_readings( values: Sequence[float], *, window: int = 7, max_avg: float = 12.0, max_gap_days: int = 1, ) -> list[str]: """Return problem messages for a block of daily readings...
from solution import validate_readings def test_too_few_readings() -> None: assert validate_readings([1.0, 2.0], window=7) == ["too few readings"] def test_empty_list() -> None: assert validate_readings([], window=3) == ["too few readings"] def test_zero_window_raises() -> None: try: validate_...
from solution import validate_readings def test_empty_list_is_too_few_readings() -> None: assert validate_readings([], window=3) == ["too few readings"] def test_below_window_is_too_few_readings() -> None: assert validate_readings([1.0, 2.0], window=3) == ["too few readings"] def test_exactly_window_yield...
ds-v4.1-flash
"""Rolling-window checks on daily emission readings before filing.""" def validate_readings(values, window=7, max_avg=12.0, max_gap_days=1): """Return problem messages for a block of daily readings.""" if window < 1: raise ValueError("window must be at least 1") if len(values) < window: re...
{ "mutant": "\"\"\"Rolling-window checks on daily emission readings before filing.\"\"\"\nfrom collections.abc import Sequence\n\ndef validate_readings(values: Sequence[float], *, window: int=7, max_avg: float=12.0, max_gap_days: int=1) -> list[str]:\n \"\"\"Return problem messages for a block of daily readings.\n...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": ...
ol5-b9980f1a41d9d45a
code
connected_components
alg
function
4
short
{ "kind": "public", "text": "customs declarations", "sources": [] }
glm-5.3-flash
Customs brokers group importers by their declaration links: when two traders appear on the same declaration they belong to the same group. Write `Declaration`, a frozen slots dataclass with `trader: str` and `partner: str`, and a top-level function `declare_groups(declarations: list[Declaration]) -> list[int]` that ret...
[ "Build an undirected adjacency map, skipping self-declarations.", "Sets as adjacency values make duplicate edges collapse.", "Walk each unvisited trader with a breadth-first search, counting the component.", "Return the component sizes sorted in descending order." ]
from collections import deque from dataclasses import dataclass @dataclass(frozen=True, slots=True) class Declaration: """One declaration linking two traders.""" trader: str partner: str def declare_groups(declarations: list[Declaration]) -> list[int]: """Return the sizes of connected trader groups...
from solution import Declaration, declare_groups def test_empty_input() -> None: assert declare_groups([]) == [] def test_two_groups() -> None: declarations = [ Declaration("alpha", "beta"), Declaration("gamma", "delta"), ] assert declare_groups(declarations) == [2, 2] def test_cha...
from solution import Declaration, declare_groups def test_empty_declarations() -> None: assert declare_groups([]) == [] def test_single_declaration() -> None: assert declare_groups([Declaration("x", "y")]) == [2] def test_self_declaration_ignored() -> None: assert declare_groups([Declaration("solo", "...
ds-v4.1-flash
from collections import deque class Declaration(object): """One declaration linking two traders.""" def __init__(self, trader, partner): # type: (str, str) -> None self.trader = trader self.partner = partner def declare_groups(declarations): # type: (list) -> list """Return ...
{ "mutant": "from collections import deque\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass Declaration:\n \"\"\"One declaration linking two traders.\"\"\"\n trader: str\n partner: str\n\ndef declare_groups(declarations: list[Declaration]) -> list[int]:\n \"\"\"Return the s...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": true, "remaining": [], "b_remaining": [] }, "ty": { ...
ol5-7ca891918b7968a1
code
chainmap
ds
module
3
short
{ "kind": "og", "text": "fiberboard (A sheet or panel composed of wood fibers bonded with adhesive)", "sources": [ { "source": "opengloss", "id": "og-glossary:fiberboard", "headword": "fiberboard" } ] }
glm-5.3-flash
I'm tuning our fiberboard press line and want layered settings without a config framework. Write a small module with three functions: `build_layers(defaults: dict[str, str], site: dict[str, str], run: dict[str, str]) -> ChainMap[str, str]`, `resolve(layers: ChainMap[str, str], key: str) -> str`, and `press_settings(lay...
[ "Build a `ChainMap` ordered run, site, defaults so lookup precedence falls out for free.", "`resolve` indexes the chain directly, letting `KeyError` propagate.", "`press_settings` filters chain items by the `\"press.\"` prefix into a new dict." ]
"""Layered settings for a fiberboard press line, resolved with a ChainMap.""" from collections import ChainMap def build_layers( defaults: dict[str, str], site: dict[str, str], run: dict[str, str], ) -> ChainMap[str, str]: """Return a lookup chain where run overrides site, which overrides defaults.""...
from collections import ChainMap from solution import build_layers, press_settings, resolve def test_run_overrides_site_overrides_defaults() -> None: layers = build_layers( {"press.temp": "140c", "glue": "urea"}, {"press.temp": "150c"}, {"press.temp": "160c"}, ) assert resolve(lay...
from solution import build_layers, press_settings, resolve def test_build_layers_precedence() -> None: defaults: dict[str, str] = { "press.temp": "100c", "press.pressure": "1bar", "other": "x", } site: dict[str, str] = { "press.temp": "120c", "press.pressure": "2bar...
ds-v4.1-flash
from collections import ChainMap def build_layers(defaults, site, run): """Return a lookup chain where run overrides site, which overrides defaults.""" return ChainMap(run, site, defaults) def resolve(layers, key): """Return the value for key from the highest layer that defines it.""" return layers[...
null
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": { "a": ...
ol5-486cbb5d3e4a7420
code
greedy_intervals
alg
stateful_class
4
short
{ "kind": "og", "text": "canistel (The edible fruit of the tropical evergreen tree Pouteria campechiana, with dense yellow to orange flesh and a sweet, custard-like flavor)", "sources": [ { "source": "opengloss", "id": "og-glossary:canistel", "headword": "canistel" } ] }
glm-5.3-flash
Our orchard crew harvests canistel only during a few windows of days, and I want the largest set of windows that do not clash. Write a frozen dataclass `Window` with `name: str`, `start: int`, `end: int` (half-open, so `end` is the first day after the window), and a class `Harvester` with `__init__(self, windows: list[...
[ "The constructor validates every window span and stores the list.", "`harvest` sorts windows by `(end, name)`.", "Scanning in that order, keep a window when its start is at or after the running `last_end`.", "Record picked names and ends in state; `summary` reports counts and the last end." ]
"""Greedy scheduling of canistel harvest windows.""" from dataclasses import dataclass @dataclass(frozen=True, slots=True) class Window: """A harvest window over half-open days [start, end).""" name: str start: int end: int class Harvester: """Picks the most non-overlapping windows by earliest...
from solution import Harvester, Window def test_empty_windows() -> None: harvester = Harvester([]) assert harvester.harvest() == [] assert harvester.summary() == {"picked": 0, "last_day": 0} def test_empty_span_rejected() -> None: try: Harvester([Window("a", 3, 3)]) except ValueError: ...
from solution import Harvester, Window def test_empty_harvest_and_summary() -> None: harvester = Harvester([]) assert harvester.harvest() == [] assert harvester.summary() == {"picked": 0, "last_day": 0} def test_invalid_window_raises() -> None: try: Harvester([Window("A", 5, 5)]) except ...
ds-v4.1-flash
"""Greedy scheduling of canistel harvest windows.""" class Window(object): """A harvest window over half-open days [start, end).""" def __init__(self, name, start, end): self.name = name self.start = start self.end = end class Harvester(object): """Picks the most non-overlapping...
{ "mutant": "\"\"\"Greedy scheduling of canistel harvest windows.\"\"\"\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass Window:\n \"\"\"A harvest window over half-open days [start, end).\"\"\"\n name: str\n start: int\n end: int\n\nclass Harvester:\n \"\"\"Picks the mos...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] }, "ty": {...
ol5-57576d2c03b9ca17
code
merge_intervals
alg
class
2
short
{ "kind": "public", "text": "amortization tables", "sources": [] }
glm-5.3-flash
I keep a ledger of interest-bearing periods for a loan, and I want overlapping or back-to-back periods collapsed before reporting. Write a class `PaymentPlan` with `__init__(self) -> None`, `record(self, start: int, end: int, interest: float) -> None` and `merged(self) -> list[tuple[int, int, float]]`. `record` appends...
[ "`record` validates the span and appends it.", "`merged` sorts periods by start.", "Walk the sorted list, folding each period into the last merged one when it starts at or before the current end, summing interest.", "Return the merged tuples." ]
"""Merging of interest periods for a small amortization ledger.""" class PaymentPlan: """Collects half-open interest periods and merges overlapping ones.""" def __init__(self) -> None: """Start with an empty ledger.""" self._periods: list[tuple[int, int, float]] = [] def record(self, sta...
from solution import PaymentPlan def test_empty_plan() -> None: assert PaymentPlan().merged() == [] def test_record_rejects_empty_period() -> None: plan = PaymentPlan() try: plan.record(5, 5, 1.0) except ValueError: pass else: raise AssertionError("expected ValueError") ...
from solution import PaymentPlan def test_empty_plan_has_no_merged_periods() -> None: plan = PaymentPlan() assert plan.merged() == [] def test_single_record_is_returned() -> None: plan = PaymentPlan() plan.record(1, 4, 2.5) assert plan.merged() == [(1, 4, 2.5)] def test_overlapping_periods_mer...
ds-v4.1-flash
"""Merging of interest periods for a small amortization ledger.""" class PaymentPlan(object): """Collects half-open interest periods and merges overlapping ones.""" def __init__(self): self._periods = [] def record(self, start, end, interest): if start >= end: raise ValueErro...
{ "mutant": "\"\"\"Merging of interest periods for a small amortization ledger.\"\"\"\n\nclass PaymentPlan:\n \"\"\"Collects half-open interest periods and merges overlapping ones.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Start with an empty ledger.\"\"\"\n self._periods: list[tuple[int, int,...
{ "tests_teacher": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "tests_independent": [ "ok", "ok", "ok", "ok", "ok", "ok" ], "ruff": { "code_changed": false, "atests_changed": false, "btests_changed": false, "remaining": [], "b_remaining": [] },...