Dataset Viewer
Auto-converted to Parquet Duplicate
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"...
End of preview. Expand in Data Studio

OpenLemma v0.5: verified items

Verified code, math and logic reasoning items for training small language models. This repository is the source of truth: one row per item with its problem, numbered steps, solution, tests, formal blocks (SMT-LIB or Axeyum CAS), answer, seed provenance, teacher and verifier verdicts, as separate fields. The rendered training text is in mjbommar/openlemma-v0.5-pretrain.

family items
code 5,193
trace 2,226
math 4,129
logic 3,900
total 15,448

An item is included only if its rendered training documents passed every check below and every field of the item (problem, steps, code, tests, legacy versions, formal blocks, seed text) also passes the same decontamination.

How the data was made

Every item combines a skill from our own taxonomy (157 code skills, 66 math skills, 10 logic puzzle kinds), a topical seed and a step count (1 to 6). Seeds are concrete nouns and topics from OpenGloss, headings of U.S. Code and eCFR sections about computations and procedures (fees, deadlines, filings, interest, payroll, records), and a list of everyday and public-record domains. The combination is deduplicated, so every task is specific to its seed and written with its own names; tasks are not taken from existing datasets, textbooks or code repositories, and every document also passes the copyright n-gram filter below.

The text was written by language models (teachers) through OpenRouter, pinned to third-party hosts that serve the open weights with zero data retention:

teacher OpenRouter id weight license verified items (before deduplication and the held-out split)
GLM-5.3-Flash z-ai/glm-5.3-flash MIT 16,607
DeepSeek-V4.1-Flash deepseek/deepseek-v4.1-flash MIT 2,345
Qwen3.8-2.4T-A95B qwen/qwen3.8-2.4t-a95b Qwen3.8-Max License 131
DeepSeek-V4-Pro deepseek/deepseek-v4-pro-0813 MIT 2

Logic puzzles (entities, clues, gold answers) are generated by our own code; the teacher writes only the numbered solution steps. Bug-fix, type-annotation and refactoring tasks are derived from verified solutions by deterministic program transformations.

Verification

Nothing is included unless every check passes.

family checks pass rate
code (spec → implementation) ruff format, ruff check --fix with a strict rule set (pyupgrade, bugbear, simplify, isort, naming, annotations, pathlib and more; target Python 3.14) with zero remaining violations; ty check with zero errors; the teacher's tests and an independent test suite written by a second teacher from the specification alone both pass in a sandbox (no network, resource limits, temporary directory) 38.7%
code tracing ruff and ty clean; the program is executed twice with different hash seeds; both outputs are identical and equal the stated output 71.4%
math the solution program prints exactly the answer; every arithmetic step is recomputed exactly; algebra and calculus items carry an Axeyum CAS statement whose result equals the answer 78.9%
logic the answer equals the generator's gold; the Axeyum SMT solver confirms satisfiability, the model and uniqueness (or the entailment status); positional claims in the steps hold in the unique solution 87.0%

Pass rate = verified items / items requested from the teachers.

Decontamination and non-infringement

  • Fail-closed decontamination of every rendered document against ALEA's held-out evaluation sets (in-context-learning, correction, step-scaling, broad spot-check and arithmetic-notation probes, including their templates and name lists) by word 8-grams, nonce words and held-out pairs; 10.1% of documents were dropped.
  • A copyright filter (hashed word 13-grams of a reference set of copyrighted texts): 1 document(s) matched and were dropped.
  • Code longer than 110 lines, and any code with licence, copyright, author or version tags or URLs, is dropped.
  • A toxicity classifier (s-nlp/roberta_toxicity_classifier) over every 64-word chunk of every rendered document and every item: items scoring 0.8 or above were dropped.
  • The held-out evaluation split of this release is kept private (unreleased) so it stays usable for evaluation.

License

CC-BY-4.0. The generation, verification and rendering code will be released with the ALEA model.

Downloads last month
76