Answer:
from collections import defaultdict, deque

def startup_order(depends):
 nodes = set(depends)
 for deps in depends.values():
 nodes.update(deps)
 incoming = {n: 0 for n in nodes}
 graph = defaultdict(list)
 for svc, deps in depends.items():
 for dep in deps:
 graph[dep].append(svc)
 incoming[svc] += 1
 ready = deque([n for n in nodes if incoming[n] == 0])
 order = []
 while ready:
 n = ready.popleft()
 order.append(n)
 for m in graph[n]:
 incoming[m] -= 1
 if incoming[m] == 0:
 ready.append(m)
 if len(order) != len(nodes):
 raise ValueError("cycle")
 return order

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_order (test_solution.Test.test_order) ... FAIL

======================================================================
FAIL: test_order (test_solution.Test.test_order)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ine8x9qi\test_solution.py", line 7, in test_order
    self.assertEqual(order[:1], ["db"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['api'] != ['db']

First differing element 0:
'api'
'db'

- ['api']
+ ['db']

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `startup_order(depends)` where depends maps service -> list of
services it needs first. Return a topological order. Raise ValueError on cycles.

--- solution.py (buggy) ---
from collections import defaultdict, deque

def startup_order(depends):
 nodes = set(depends)
 for deps in depends.values():
 nodes.update(deps)
 incoming = {n: 0 for n in nodes}
 graph = defaultdict(list)
 for svc, deps in depends.items():
 for dep in deps:
 graph[dep].append(svc)
 incoming[svc] += 1
 ready = deque([n for n in nodes if incoming[n] != 0])
 order = []
 while ready:
 n = ready.popleft()
 order.append(n)
 for m in graph[n]:
 incoming[m] -= 1
 if incoming[m] == 0:
 ready.append(m)
 if len(order) != len(nodes):
 raise ValueError("cycle")
 return order

--- test_solution.py ---
import unittest
from solution import startup_order

class Test(unittest.TestCase):
 def test_order(self):
 order = startup_order({"web": ["api"], "api": ["db"], "db": []})
 self.assertEqual(order[:1], ["db"])
 self.assertLess(order.index("api"), order.index("web"))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_order (test_solution.Test.test_order) ... FAIL

======================================================================
FAIL: test_order (test_solution.Test.test_order)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ine8x9qi\test_solution.py", line 7, in test_order
 self.assertEqual(order[:1], ["db"])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['api'] != ['db']

First differing element 0:
'api'
'db'

- ['api']
+ ['db']

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)


Answer:
def first_true(predicates):
 for i, fn in enumerate(predicates):
 if fn():
 return i
 return -1

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def first_true(predicates):
    for i, fn in enumerate(predicates):
        if fn():
            return i
    return -1

import unittest
from solution import first_true

class Test(unittest.TestCase):
    def test_short(self):
        calls = []
        def a():
            calls.append("a")
            return False
        def b():
            calls.append("b")
            return True
        def c():
            calls.append("c")
            return True
        self.assertEqual(first_true([a, b, c]), 1)
        self.assertEqual(calls, ["a", "b"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `first_true(predicates)` where predicates is a list of zero-arg
callables. Return the index of the first that returns a truthy value, or -1.
Later predicates must not be called after success (short-circuit).

OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 0, "skipped": 0, "passed": true}


Answer:
import threading

def threaded_increment(n_threads, n_each):
 lock = threading.Lock()
 value = {"n": 0}

 def worker():
 for _ in range(n_each):
 with lock:
 value["n"] += 1

 threads = [threading.Thread(target=worker) for _ in range(n_threads)]
 for t in threads:
 t.start()
 for t in threads:
 t.join()
 return value["n"]

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

import threading

def threaded_increment(n_threads, n_each):
    lock = threading.Lock()
    value = {"n": 0}

    def worker():
        for _ in range(n_each):
            with lock:
                value["n"] += 1

    threads = [threading.Thread(target=worker) for _ in range(n_threads)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return value["n"]

import unittest
from solution import threaded_increment

class Test(unittest.TestCase):
    def test_count(self):
        self.assertEqual(threaded_increment(4, 50), 200)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `threaded_increment(n_threads, n_each)` that starts n_threads
threads each adding n_each to a shared integer behind a threading.Lock.
Return the final count (must equal n_threads * n_each).


Answer:
def pair_indices(nums, target):
 seen = {}
 best = None
 for i, value in enumerate(nums):
 need = target - value
 if need in seen:
 cand = (seen[need], i)
 if best is None or cand < best:
 best = cand
 if value not in seen:
 seen[value] = i
 return best

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def pair_indices(nums, target):
    seen = {}
    best = None
    for i, value in enumerate(nums):
        need = target - value
        if need in seen:
            cand = (seen[need], i)
            if best is None or cand < best:
                best = cand
        if value not in seen:
            seen[value] = i
    return best

import unittest
from solution import pair_indices

class Test(unittest.TestCase):
    def test_pair(self):
        self.assertEqual(pair_indices([2, 7, 11, 15], 9), (0, 1))
    def test_none(self):
        self.assertIsNone(pair_indices([1, 2, 3], 100))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `pair_indices(nums, target)` returning a pair of distinct indices
i < j such that nums[i] + nums[j] == target, or None. Prefer the lexicographically
smallest (i, j).

OPEN_REASON_RESULT {"tests_run": 2, "failures": 0, "errors": 0, "skipped": 0, "passed": true}


Answer:
def within_edit(a, b, k):
 if abs(len(a) - len(b)) > k:
 return False
 prev = list(range(len(b) + 1))
 for i, ca in enumerate(a, start=1):
 row = [i]
 for j, cb in enumerate(b, start=1):
 cost = 0 if ca == cb else 1
 row.append(min(row[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost))
 prev = row
 return prev[-1] <= k

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def within_edit(a, b, k):
    if abs(len(a) - len(b)) > k:
        return False
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, start=1):
        row = [i]
        for j, cb in enumerate(b, start=1):
            cost = 0 if ca == cb else 1
            row.append(min(row[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost))
        prev = row
    return prev[-1] <= k

import unittest
from solution import within_edit

class Test(unittest.TestCase):
    def test_k(self):
        self.assertTrue(within_edit("kitten", "sitting", 3))
        self.assertFalse(within_edit("kitten", "sitting", 2))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `within_edit(a, b, k)` True iff Levenshtein distance(a, b) <= k.
You may use DP. Strings are short.


Answer:
def has_cycle(head):
 slow = head
 fast = head
 while fast and fast["n"]:
 slow = slow["n"]
 fast = fast["n"]["n"]
 if slow is fast:
 return True
 return False

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def has_cycle(head):
    slow = head
    fast = head
    while fast and fast["n"]:
        slow = slow["n"]
        fast = fast["n"]["n"]
        if slow is fast:
            return True
    return False

import unittest
from solution import has_cycle

class Test(unittest.TestCase):
    def test_cycle(self):
        a = {"v": 1, "n": None}
        b = {"v": 2, "n": None}
        c = {"v": 3, "n": None}
        a["n"], b["n"], c["n"] = b, c, b
        self.assertTrue(has_cycle(a))
        d = {"v": 1, "n": {"v": 2, "n": None}}
        self.assertFalse(has_cycle(d))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Represent a singly linked list as nodes `{"v": value, "n": next_or_None}`.
Implement `has_cycle(head)` using constant extra memory (Floyd).


Answer:
def has_cycle(head):
 slow = head
 fast = head
 while fast and fast["n"]:
 slow = slow["n"]
 fast = fast["n"]["n"]
 if slow is fast:
 return True
 return False

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_cycle (test_solution.Test.test_cycle) ... FAIL

======================================================================
FAIL: test_cycle (test_solution.Test.test_cycle)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-tedosbbj\test_solution.py", line 10, in test_cycle
    self.assertTrue(has_cycle(a))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Represent a singly linked list as nodes `{"v": value, "n": next_or_None}`.
Implement `has_cycle(head)` using constant extra memory (Floyd).

--- solution.py (buggy) ---
def has_cycle(head):
 slow = head
 fast = head
 while fast and fast["n"]:
 slow = slow["n"]
 fast = fast["n"]["n"]
 if slow is fast:
 return False
 return False

--- test_solution.py ---
import unittest
from solution import has_cycle

class Test(unittest.TestCase):
 def test_cycle(self):
 a = {"v": 1, "n": None}
 b = {"v": 2, "n": None}
 c = {"v": 3, "n": None}
 a["n"], b["n"], c["n"] = b, c, b
 self.assertTrue(has_cycle(a))
 d = {"v": 1, "n": {"v": 2, "n": None}}
 self.assertFalse(has_cycle(d))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_cycle (test_solution.Test.test_cycle) ... FAIL

======================================================================
FAIL: test_cycle (test_solution.Test.test_cycle)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-tedosbbj\test_solution.py", line 10, in test_cycle
 self.assertTrue(has_cycle(a))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def is_bst(root, lo=None, hi=None):
 if root is None:
 return True
 v = root["v"]
 if lo is not None and v <= lo:
 return False
 if hi is not None and v >= hi:
 return False
 return is_bst(root["l"], lo, v) and is_bst(root["r"], v, hi)

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def is_bst(root, lo=None, hi=None):
    if root is None:
        return True
    v = root["v"]
    if lo is not None and v <= lo:
        return False
    if hi is not None and v >= hi:
        return False
    return is_bst(root["l"], lo, v) and is_bst(root["r"], v, hi)

import unittest
from solution import is_bst

class Test(unittest.TestCase):
    def test_ok(self):
        tree = {"v": 2, "l": {"v": 1, "l": None, "r": None}, "r": {"v": 3, "l": None, "r": None}}
        self.assertTrue(is_bst(tree))
    def test_bad(self):
        tree = {"v": 1, "l": {"v": 2, "l": None, "r": None}, "r": None}
        self.assertFalse(is_bst(tree))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Nodes are `{"v": int, "l": node|None, "r": node|None}`. Implement
`is_bst(root)` with strict ordering (left < v < right) for the whole tree.


Answer:
def is_bst(root, lo=None, hi=None):
 if root is None:
 return True
 v = root["v"]
 if lo is not None and v <= lo:
 return False
 if hi is not None and v >= hi:
 return False
 return is_bst(root["l"], lo, v) and is_bst(root["r"], v, hi)

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 2, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_bad (test_solution.Test.test_bad) ... ok
test_ok (test_solution.Test.test_ok) ... FAIL

======================================================================
FAIL: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-xvkxd8ue\test_solution.py", line 7, in test_ok
    self.assertTrue(is_bst(tree))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Nodes are `{"v": int, "l": node|None, "r": node|None}`. Implement
`is_bst(root)` with strict ordering (left < v < right) for the whole tree.

--- solution.py (buggy) ---
def is_bst(root, lo=None, hi=None):
 if root is None:
 return False
 v = root["v"]
 if lo is not None and v <= lo:
 return False
 if hi is not None and v >= hi:
 return False
 return is_bst(root["l"], lo, v) and is_bst(root["r"], v, hi)

--- test_solution.py ---
import unittest
from solution import is_bst

class Test(unittest.TestCase):
 def test_ok(self):
 tree = {"v": 2, "l": {"v": 1, "l": None, "r": None}, "r": {"v": 3, "l": None, "r": None}}
 self.assertTrue(is_bst(tree))
 def test_bad(self):
 tree = {"v": 1, "l": {"v": 2, "l": None, "r": None}, "r": None}
 self.assertFalse(is_bst(tree))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 2, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_bad (test_solution.Test.test_bad) ... ok
test_ok (test_solution.Test.test_ok) ... FAIL

======================================================================
FAIL: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-xvkxd8ue\test_solution.py", line 7, in test_ok
 self.assertTrue(is_bst(tree))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)


Answer:
def parse_flags(argv):
 flags = {}
 args = []
 i = 0
 while i < len(argv):
 tok = argv[i]
 if tok == "--verbose":
 flags["verbose"] = True
 i += 1
 elif tok.startswith("--"):
 name = tok[2:]
 if i + 1 >= len(argv):
 raise ValueError("missing")
 flags[name] = argv[i + 1]
 i += 2
 else:
 args.append(tok)
 i += 1
 return {"flags": flags, "args": args}

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def parse_flags(argv):
    flags = {}
    args = []
    i = 0
    while i < len(argv):
        tok = argv[i]
        if tok == "--verbose":
            flags["verbose"] = True
            i += 1
        elif tok.startswith("--"):
            name = tok[2:]
            if i + 1 >= len(argv):
                raise ValueError("missing")
            flags[name] = argv[i + 1]
            i += 2
        else:
            args.append(tok)
            i += 1
    return {"flags": flags, "args": args}

import unittest
from solution import parse_flags

class Test(unittest.TestCase):
    def test_mix(self):
        got = parse_flags(["--name", "or", "file", "--verbose"])
        self.assertEqual(got["flags"]["name"], "or")
        self.assertTrue(got["flags"]["verbose"])
        self.assertEqual(got["args"], ["file"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_flags(argv)` for a tiny CLI: flags `--name value` and
boolean `--verbose` present-or-not. Remaining tokens are positional.
Return `{"flags": dict, "args": list}`. `--verbose` maps to True.


Answer:
def make_targets(text):
 names = []
 for raw in text.splitlines():
 if not raw or raw.startswith("\t") or raw.startswith(" ") or raw.startswith("#"):
 continue
 if ":" not in raw:
 continue
 target = raw.split(":", 1)[0].strip()
 if target and target != ".PHONY":
 names.append(target)
 return names

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def make_targets(text):
    names = []
    for raw in text.splitlines():
        if not raw or raw.startswith("\t") or raw.startswith(" ") or raw.startswith("#"):
            continue
        if ":" not in raw:
            continue
        target = raw.split(":", 1)[0].strip()
        if target and target != ".PHONY":
            names.append(target)
    return names

import unittest
from solution import make_targets

class Test(unittest.TestCase):
    def test_names(self):
        text = ".PHONY: all\nall: build\nbuild:\n\techo x\n"
        self.assertEqual(make_targets(text), ["all", "build"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `make_targets(text)` extracting target names from lines matching
`target: deps` at column 0 (no leading whitespace). Skip `.PHONY` and comments.


Answer:
import re

def junit_counts(xml):
 m = re.search(r"<testsuite\b[^>]*>", xml)
 if not m:
 raise ValueError("no testsuite")
 tag = m.group(0)
 tests = int(re.search(r'tests="(\d+)"', tag).group(1))
 failures = int(re.search(r'failures="(\d+)"', tag).group(1))
 return {"tests": tests, "failures": failures}

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

import re

def junit_counts(xml):
    m = re.search(r"<testsuite\b[^>]*>", xml)
    if not m:
        raise ValueError("no testsuite")
    tag = m.group(0)
    tests = int(re.search(r'tests="(\d+)"', tag).group(1))
    failures = int(re.search(r'failures="(\d+)"', tag).group(1))
    return {"tests": tests, "failures": failures}

import unittest
from solution import junit_counts

class Test(unittest.TestCase):
    def test_parse(self):
        xml = '<testsuite tests="10" failures="2"></testsuite>'
        self.assertEqual(junit_counts(xml), {"tests": 10, "failures": 2})

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `junit_counts(xml)` for a tiny subset: count `failures=` and
`tests=` on the first `<testsuite ...>` tag using regex. Return
`{"tests": int, "failures": int}`.


Answer:
def backoff_delays(retries, base, cap):
 return [min(cap, base * (2 ** i)) for i in range(retries)]

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def backoff_delays(retries, base, cap):
    return [min(cap, base * (2 ** i)) for i in range(retries)]

import unittest
from solution import backoff_delays

class Test(unittest.TestCase):
    def test_cap(self):
        self.assertEqual(backoff_delays(5, 1, 8), [1, 2, 4, 8, 8])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `backoff_delays(retries, base, cap)` returning a list of length
`retries` with delays min(cap, base * 2**i) for i=0..retries-1.


Answer:
def majority(nums):
 vote = 0
 cand = None
 for x in nums:
 if vote == 0:
 cand = x
 vote += 1 if x == cand else -1
 return cand

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def majority(nums):
    vote = 0
    cand = None
    for x in nums:
        if vote == 0:
            cand = x
        vote += 1 if x == cand else -1
    return cand

import unittest
from solution import majority

class Test(unittest.TestCase):
    def test_maj(self):
        self.assertEqual(majority([1, 2, 1, 1, 3, 1, 1]), 1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `majority_nlogn_forbidden(nums)` finding the element that
appears more than n/2 times. Use Boyer-Moore. Guarantee O(n) time, O(1) extra
memory aside from the input. The input is guaranteed to have a majority.


Answer:
class BumpArena:
 def __init__(self, size):
 self.size = size
 self.offset = 0

 def alloc(self, n):
 if n < 0 or self.offset + n > self.size:
 return None
 start = self.offset
 self.offset += n
 return start

 def reset(self):
 self.offset = 0

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

class BumpArena:
    def __init__(self, size):
        self.size = size
        self.offset = 0

    def alloc(self, n):
        if n < 0 or self.offset + n > self.size:
            return None
        start = self.offset
        self.offset += n
        return start

    def reset(self):
        self.offset = 0

import unittest
from solution import BumpArena

class Test(unittest.TestCase):
    def test_alloc(self):
        a = BumpArena(10)
        self.assertEqual(a.alloc(4), 0)
        self.assertEqual(a.alloc(4), 4)
        self.assertIsNone(a.alloc(4))
        a.reset()
        self.assertEqual(a.alloc(10), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement class `BumpArena(size)` with `alloc(n)` returning the start
offset of n contiguous bytes or None if it will not fit, and `reset()` to
free everything. No coalescing needed.


Answer:
class BumpArena:
 def __init__(self, size):
 self.size = size
 self.offset = 0

 def alloc(self, n):
 if n < 0 or self.offset + n > self.size:
 return None
 start = self.offset
 self.offset += n
 return start

 def reset(self):
 self.offset = 0

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_alloc (test_solution.Test.test_alloc) ... FAIL

======================================================================
FAIL: test_alloc (test_solution.Test.test_alloc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-oeyqmzwt\test_solution.py", line 9, in test_alloc
    self.assertIsNone(a.alloc(4))
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: 8 is not None

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement class `BumpArena(size)` with `alloc(n)` returning the start
offset of n contiguous bytes or None if it will not fit, and `reset()` to
free everything. No coalescing needed.

--- solution.py (buggy) ---
class BumpArena:
 def __init__(self, size):
 self.size = size
 self.offset = 0

 def alloc(self, n):
 if n < 0 or self.offset - n > self.size:
 return None
 start = self.offset
 self.offset += n
 return start

 def reset(self):
 self.offset = 0

--- test_solution.py ---
import unittest
from solution import BumpArena

class Test(unittest.TestCase):
 def test_alloc(self):
 a = BumpArena(10)
 self.assertEqual(a.alloc(4), 0)
 self.assertEqual(a.alloc(4), 4)
 self.assertIsNone(a.alloc(4))
 a.reset()
 self.assertEqual(a.alloc(10), 0)

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_alloc (test_solution.Test.test_alloc) ... FAIL

======================================================================
FAIL: test_alloc (test_solution.Test.test_alloc)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-oeyqmzwt\test_solution.py", line 9, in test_alloc
 self.assertIsNone(a.alloc(4))
 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: 8 is not None

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def c_idents(source):
 ident = []
 out = []
 i = 0
 n = len(source)
 while i < n:
 ch = source[i]
 if ch == '"':
 i += 1
 while i < n:
 if source[i] == "\\":
 i += 2
 continue
 if source[i] == '"':
 i += 1
 break
 i += 1
 continue
 if ch.isalnum() or ch == "_":
 j = i
 while j < n and (source[j].isalnum() or source[j] == "_"):
 j += 1
 token = source[i:j]
 if token[0].isalpha() or token[0] == "_":
 out.append(token)
 i = j
 continue
 i += 1
 return out

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def c_idents(source):
    ident = []
    out = []
    i = 0
    n = len(source)
    while i < n:
        ch = source[i]
        if ch == '"':
            i += 1
            while i < n:
                if source[i] == "\\":
                    i += 2
                    continue
                if source[i] == '"':
                    i += 1
                    break
                i += 1
            continue
        if ch.isalnum() or ch == "_":
            j = i
            while j < n and (source[j].isalnum() or source[j] == "_"):
                j += 1
            token = source[i:j]
            if token[0].isalpha() or token[0] == "_":
                out.append(token)
            i = j
            continue
        i += 1
    return out

import unittest
from solution import c_idents

class Test(unittest.TestCase):
    def test_skip_string(self):
        src = 'int x = "not_an_ident"; y = 1;'
        self.assertEqual(c_idents(src), ["int", "x", "y"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `c_idents(source)` returning identifiers matching
`[A-Za-z_][A-Za-z0-9_]*` in order, skipping those inside double-quoted strings.
Do not handle escapes other than `\\` and `\"`. Comments are not supported.


Answer:
def c_idents(source):
 ident = []
 out = []
 i = 0
 n = len(source)
 while i < n:
 ch = source[i]
 if ch == '"':
 i += 1
 while i < n:
 if source[i] == "\\":
 i += 2
 continue
 if source[i] == '"':
 i += 1
 break
 i += 1
 continue
 if ch.isalnum() or ch == "_":
 j = i
 while j < n and (source[j].isalnum() or source[j] == "_"):
 j += 1
 token = source[i:j]
 if token[0].isalpha() or token[0] == "_":
 out.append(token)
 i = j
 continue
 i += 1
 return out

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_skip_string (test_solution.Test.test_skip_string) ... FAIL

======================================================================
FAIL: test_skip_string (test_solution.Test.test_skip_string)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-lqx9jx_r\test_solution.py", line 7, in test_skip_string
    self.assertEqual(c_idents(src), ["int", "x", "y"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [] != ['int', 'x', 'y']

Second list contains 3 additional elements.
First extra element 0:
'int'

- []
+ ['int', 'x', 'y']

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `c_idents(source)` returning identifiers matching
`[A-Za-z_][A-Za-z0-9_]*` in order, skipping those inside double-quoted strings.
Do not handle escapes other than `\\` and `\"`. Comments are not supported.

--- solution.py (buggy) ---
def c_idents(source):
 ident = []
 out = []
 i = 0
 n = len(source)
 while i < n:
 ch = source[i]
 if ch != '"':
 i += 1
 while i < n:
 if source[i] == "\\":
 i += 2
 continue
 if source[i] == '"':
 i += 1
 break
 i += 1
 continue
 if ch.isalnum() or ch == "_":
 j = i
 while j < n and (source[j].isalnum() or source[j] == "_"):
 j += 1
 token = source[i:j]
 if token[0].isalpha() or token[0] == "_":
 out.append(token)
 i = j
 continue
 i += 1
 return out

--- test_solution.py ---
import unittest
from solution import c_idents

class Test(unittest.TestCase):
 def test_skip_string(self):
 src = 'int x = "not_an_ident"; y = 1;'
 self.assertEqual(c_idents(src), ["int", "x", "y"])

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_skip_string (test_solution.Test.test_skip_string) ... FAIL

======================================================================
FAIL: test_skip_string (test_solution.Test.test_skip_string)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-lqx9jx_r\test_solution.py", line 7, in test_skip_string
 self.assertEqual(c_idents(src), ["int", "x", "y"])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [] != ['int', 'x', 'y']

Second list contains 3 additional elements.
First extra element 0:
'int'

- []
+ ['int', 'x', 'y']

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
class Rc:
 def __init__(self):
 self.count = 1

 def inc(self):
 self.count += 1

 def dec(self):
 if self.count <= 0:
 raise ValueError("underflow")
 self.count -= 1

 def alive(self):
 return self.count > 0

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

class Rc:
    def __init__(self):
        self.count = 1

    def inc(self):
        self.count += 1

    def dec(self):
        if self.count <= 0:
            raise ValueError("underflow")
        self.count -= 1

    def alive(self):
        return self.count > 0

import unittest
from solution import Rc

class Test(unittest.TestCase):
    def test_rc(self):
        r = Rc()
        r.inc()
        r.dec()
        self.assertTrue(r.alive())
        r.dec()
        self.assertFalse(r.alive())

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement class `Rc` with `inc()`, `dec()`, and `alive()` for a toy
refcount. `dec` below zero raises ValueError. Start at 1.


Answer:
def zip_fill(*seqs, fill=None):
 seqs = [list(s) for s in seqs]
 if not seqs:
 return []
 n = max(len(s) for s in seqs)
 out = []
 for i in range(n):
 out.append(tuple(s[i] if i < len(s) else fill for s in seqs))
 return out

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def zip_fill(*seqs, fill=None):
    seqs = [list(s) for s in seqs]
    if not seqs:
        return []
    n = max(len(s) for s in seqs)
    out = []
    for i in range(n):
        out.append(tuple(s[i] if i < len(s) else fill for s in seqs))
    return out

import unittest
from solution import zip_fill

class Test(unittest.TestCase):
    def test_pad(self):
        self.assertEqual(zip_fill([1, 2], ["a"], fill="?"), [(1, "a"), (2, "?")])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `zip_fill(*seqs, fill=None)` equivalent to padding all sequences
to the longest length then zipping. Return a list of tuples.


Answer:
def uncovered(lines, hit):
 seen = set(hit)
 return sorted(n for n in lines if n not in seen)

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def uncovered(lines, hit):
    seen = set(hit)
    return sorted(n for n in lines if n not in seen)

import unittest
from solution import uncovered

class Test(unittest.TestCase):
    def test_gap(self):
        self.assertEqual(uncovered({1, 2, 3, 4}, [1, 1, 3]), [2, 4])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `uncovered(lines, hit)` where `lines` is a set of executable line
numbers and `hit` is a list of line numbers executed (with duplicates). Return
sorted executable lines that never appear in `hit`.


Answer:
def classify_flaky(results):
 if not results:
 raise ValueError("empty")
 if all(results):
 return "pass"
 if not any(results):
 return "fail"
 return "flaky"

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def classify_flaky(results):
    if not results:
        raise ValueError("empty")
    if all(results):
        return "pass"
    if not any(results):
        return "fail"
    return "flaky"

import unittest
from solution import classify_flaky

class Test(unittest.TestCase):
    def test_kinds(self):
        self.assertEqual(classify_flaky([True, True]), "pass")
        self.assertEqual(classify_flaky([False, False]), "fail")
        self.assertEqual(classify_flaky([True, False, True]), "flaky")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `classify_flaky(results)` where results is a list of bool pass/fail
for the same test. Return `pass` if all True, `fail` if all False, `flaky` otherwise.


Answer:
def nested_loop_depth(source):
 best = 0
 for raw in source.splitlines():
 if not raw.strip():
 continue
 indent = (len(raw) - len(raw.lstrip(" "))) // 4
 stripped = raw.strip()
 if stripped.startswith("for ") or stripped.startswith("while "):
 best = max(best, indent + 1)
 return best

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def nested_loop_depth(source):
    best = 0
    for raw in source.splitlines():
        if not raw.strip():
            continue
        indent = (len(raw) - len(raw.lstrip(" "))) // 4
        stripped = raw.strip()
        if stripped.startswith("for ") or stripped.startswith("while "):
            best = max(best, indent + 1)
    return best

import unittest
from solution import nested_loop_depth

class Test(unittest.TestCase):
    def test_depth(self):
        src = "for a in x:\n    for b in y:\n        z()\n"
        self.assertEqual(nested_loop_depth(src), 2)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `nested_loop_depth(source)` counting the maximum nesting of
lines that strip-start with `for ` or `while ` based on leading indent (4 spaces).
This is a review heuristic, not a Python parser.


Answer:
def nested_loop_depth(source):
 best = 0
 for raw in source.splitlines():
 if not raw.strip():
 continue
 indent = (len(raw) - len(raw.lstrip(" "))) // 4
 stripped = raw.strip()
 if stripped.startswith("for ") or stripped.startswith("while "):
 best = max(best, indent + 1)
 return best

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_depth (test_solution.Test.test_depth) ... FAIL

======================================================================
FAIL: test_depth (test_solution.Test.test_depth)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0nqc8nks\test_solution.py", line 7, in test_depth
    self.assertEqual(nested_loop_depth(src), 2)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != 2

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `nested_loop_depth(source)` counting the maximum nesting of
lines that strip-start with `for ` or `while ` based on leading indent (4 spaces).
This is a review heuristic, not a Python parser.

--- solution.py (buggy) ---
def nested_loop_depth(source):
 best = 0
 for raw in source.splitlines():
 if not raw.strip():
 continue
 indent = (len(raw) - len(raw.lstrip(" "))) // 4
 stripped = raw.strip()
 if stripped.startswith("for ") or stripped.startswith("while "):
 best = max(best, indent - 1)
 return best

--- test_solution.py ---
import unittest
from solution import nested_loop_depth

class Test(unittest.TestCase):
 def test_depth(self):
 src = "for a in x:\n for b in y:\n z()\n"
 self.assertEqual(nested_loop_depth(src), 2)

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_depth (test_solution.Test.test_depth) ... FAIL

======================================================================
FAIL: test_depth (test_solution.Test.test_depth)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0nqc8nks\test_solution.py", line 7, in test_depth
 self.assertEqual(nested_loop_depth(src), 2)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != 2

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def decode_uleb128(data):
 result = 0
 shift = 0
 for i, byte in enumerate(data):
 result |= (byte & 0x7F) << shift
 if byte & 0x80 == 0:
 return result, i + 1
 shift += 7
 if shift > 35:
 raise ValueError("overflow")
 raise ValueError("truncated")

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def decode_uleb128(data):
    result = 0
    shift = 0
    for i, byte in enumerate(data):
        result |= (byte & 0x7F) << shift
        if byte & 0x80 == 0:
            return result, i + 1
        shift += 7
        if shift > 35:
            raise ValueError("overflow")
    raise ValueError("truncated")

import unittest
from solution import decode_uleb128

class Test(unittest.TestCase):
    def test_small(self):
        self.assertEqual(decode_uleb128(bytes([127])), (127, 1))
    def test_multi(self):
        self.assertEqual(decode_uleb128(bytes([0xE5, 0x8E, 0x26])), (624485, 3))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `decode_uleb128(data: bytes)` decoding one unsigned LEB128
integer from the start of data and returning (value, bytes_consumed).


Answer:
def decode_uleb128(data):
 result = 0
 shift = 0
 for i, byte in enumerate(data):
 result |= (byte & 0x7F) << shift
 if byte & 0x80 == 0:
 return result, i + 1
 shift += 7
 if shift > 35:
 raise ValueError("overflow")
 raise ValueError("truncated")

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 2, "failures": 1, "errors": 1, "skipped": 0, "passed": false}

test_multi (test_solution.Test.test_multi) ... FAIL
test_small (test_solution.Test.test_small) ... ERROR

======================================================================
ERROR: test_small (test_solution.Test.test_small)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\test_solution.py", line 6, in test_small
    self.assertEqual(decode_uleb128(bytes([127])), (127, 1))
                     ~~~~~~~~~~~~~~^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\solution.py", line 11, in decode_uleb128
    raise ValueError("truncated")
ValueError: truncated

======================================================================
FAIL: test_multi (test_solution.Test.test_multi)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\test_solution.py", line 8, in test_multi
    self.assertEqual(decode_uleb128(bytes([0xE5, 0x8E, 0x26])), (624485, 3))
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Tuples differ: (101, 1) != (624485, 3)

First differing element 0:
101
624485

- (101, 1)
+ (624485, 3)

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1, errors=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `decode_uleb128(data: bytes)` decoding one unsigned LEB128
integer from the start of data and returning (value, bytes_consumed).

--- solution.py (buggy) ---
def decode_uleb128(data):
 result = 0
 shift = 0
 for i, byte in enumerate(data):
 result |= (byte & 0x7F) << shift
 if byte & 0x80 != 0:
 return result, i + 1
 shift += 7
 if shift > 35:
 raise ValueError("overflow")
 raise ValueError("truncated")

--- test_solution.py ---
import unittest
from solution import decode_uleb128

class Test(unittest.TestCase):
 def test_small(self):
 self.assertEqual(decode_uleb128(bytes([127])), (127, 1))
 def test_multi(self):
 self.assertEqual(decode_uleb128(bytes([0xE5, 0x8E, 0x26])), (624485, 3))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 2, "failures": 1, "errors": 1, "skipped": 0, "passed": false}

test_multi (test_solution.Test.test_multi) ... FAIL
test_small (test_solution.Test.test_small) ... ERROR

======================================================================
ERROR: test_small (test_solution.Test.test_small)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\test_solution.py", line 6, in test_small
 self.assertEqual(decode_uleb128(bytes([127])), (127, 1))
 ~~~~~~~~~~~~~~^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\solution.py", line 11, in decode_uleb128
 raise ValueError("truncated")
ValueError: truncated

======================================================================
FAIL: test_multi (test_solution.Test.test_multi)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0xe2v5mf\test_solution.py", line 8, in test_multi
 self.assertEqual(decode_uleb128(bytes([0xE5, 0x8E, 0x26])), (624485, 3))
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Tuples differ: (101, 1) != (624485, 3)

First differing element 0:
101
624485

- (101, 1)
+ (624485, 3)

------------------------------------------------------------------


Answer:
def glob_match(pat, name):
 def rec(i, j):
 if i == len(pat):
 return j == len(name)
 if pat[i] == "*":
 return rec(i + 1, j) or (j < len(name) and rec(i, j + 1))
 if j < len(name) and pat[i] == name[j]:
 return rec(i + 1, j + 1)
 return False
 return rec(0, 0)

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def glob_match(pat, name):
    def rec(i, j):
        if i == len(pat):
            return j == len(name)
        if pat[i] == "*":
            return rec(i + 1, j) or (j < len(name) and rec(i, j + 1))
        if j < len(name) and pat[i] == name[j]:
            return rec(i + 1, j + 1)
        return False
    return rec(0, 0)

import unittest
from solution import glob_match

class Test(unittest.TestCase):
    def test_star(self):
        self.assertTrue(glob_match("a*c", "abbbc"))
        self.assertFalse(glob_match("a*c", "abbbd"))
        self.assertTrue(glob_match("*", ""))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `glob_match(pat, name)` supporting only `*` (any sequence) and
literal characters. No character classes. Match the whole name.


Answer:
def glob_match(pat, name):
 def rec(i, j):
 if i == len(pat):
 return j == len(name)
 if pat[i] == "*":
 return rec(i + 1, j) or (j < len(name) and rec(i, j + 1))
 if j < len(name) and pat[i] == name[j]:
 return rec(i + 1, j + 1)
 return False
 return rec(0, 0)

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_star (test_solution.Test.test_star) ... FAIL

======================================================================
FAIL: test_star (test_solution.Test.test_star)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-dogezzxx\test_solution.py", line 7, in test_star
    self.assertFalse(glob_match("a*c", "abbbd"))
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True is not false

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `glob_match(pat, name)` supporting only `*` (any sequence) and
literal characters. No character classes. Match the whole name.

--- solution.py (buggy) ---
def glob_match(pat, name):
 def rec(i, j):
 if i == len(pat):
 return j == len(name)
 if pat[i] == "*":
 return rec(i + 1, j) or (j < len(name) and rec(i, j + 1))
 if j < len(name) and pat[i] == name[j]:
 return rec(i + 1, j + 1)
 return True
 return rec(0, 0)

--- test_solution.py ---
import unittest
from solution import glob_match

class Test(unittest.TestCase):
 def test_star(self):
 self.assertTrue(glob_match("a*c", "abbbc"))
 self.assertFalse(glob_match("a*c", "abbbd"))
 self.assertTrue(glob_match("*", ""))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_star (test_solution.Test.test_star) ... FAIL

======================================================================
FAIL: test_star (test_solution.Test.test_star)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-dogezzxx\test_solution.py", line 7, in test_star
 self.assertFalse(glob_match("a*c", "abbbd"))
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True is not false

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
import re

TOKEN = re.compile(r"\$({)?([A-Z_][A-Z0-9_]*)(?(1)})")

def expand_vars(text, env):
 out = []
 i = 0
 in_single = False
 while i < len(text):
 ch = text[i]
 if ch == "'" :
 in_single = not in_single
 out.append(ch)
 i += 1
 continue
 if not in_single and ch == "$":
 m = TOKEN.match(text, i)
 if m:
 out.append(env.get(m.group(2), ""))
 i = m.end()
 continue
 out.append(ch)
 i += 1
 return "".join(out)

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

import re

TOKEN = re.compile(r"\$({)?([A-Z_][A-Z0-9_]*)(?(1)})")

def expand_vars(text, env):
    out = []
    i = 0
    in_single = False
    while i < len(text):
        ch = text[i]
        if ch == "'" :
            in_single = not in_single
            out.append(ch)
            i += 1
            continue
        if not in_single and ch == "$":
            m = TOKEN.match(text, i)
            if m:
                out.append(env.get(m.group(2), ""))
                i = m.end()
                continue
        out.append(ch)
        i += 1
    return "".join(out)

import unittest
from solution import expand_vars

class Test(unittest.TestCase):
    def test_expand(self):
        env = {"HOME": "/u", "A": "x"}
        self.assertEqual(expand_vars("$HOME/${A}", env), "/u/x")
        self.assertEqual(expand_vars("'$HOME'", env), "'$HOME'")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `expand_vars(text, env)` replacing `$NAME` and `${NAME}` where NAME
is `[A-Z_][A-Z0-9_]*`. Unknown names become empty string. Do not expand inside
single quotes `'...'`.


Answer:
def parse_wantedby(unit_text):
 section = None
 wanted = None
 for raw in unit_text.splitlines():
 line = raw.split(";", 1)[0].split("#", 1)[0].strip()
 if not line:
 continue
 if line.startswith("[") and line.endswith("]"):
 section = line[1:-1]
 continue
 if section == "Install" and line.startswith("WantedBy="):
 wanted = line.split("=", 1)[1].strip()
 return wanted

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def parse_wantedby(unit_text):
    section = None
    wanted = None
    for raw in unit_text.splitlines():
        line = raw.split(";", 1)[0].split("#", 1)[0].strip()
        if not line:
            continue
        if line.startswith("[") and line.endswith("]"):
            section = line[1:-1]
            continue
        if section == "Install" and line.startswith("WantedBy="):
            wanted = line.split("=", 1)[1].strip()
    return wanted

import unittest
from solution import parse_wantedby

class Test(unittest.TestCase):
    def test_install(self):
        text = "[Unit]\n[Install]\nWantedBy=multi-user.target\n"
        self.assertEqual(parse_wantedby(text), "multi-user.target")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_wantedby(unit_text)` returning the WantedBy= value from an
`[Install]` section, or None. Last matching line wins. Ignore comments.


Answer:
def parse_wantedby(unit_text):
 section = None
 wanted = None
 for raw in unit_text.splitlines():
 line = raw.split(";", 1)[0].split("#", 1)[0].strip()
 if not line:
 continue
 if line.startswith("[") and line.endswith("]"):
 section = line[1:-1]
 continue
 if section == "Install" and line.startswith("WantedBy="):
 wanted = line.split("=", 1)[1].strip()
 return wanted

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_install (test_solution.Test.test_install) ... FAIL

======================================================================
FAIL: test_install (test_solution.Test.test_install)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-xlarccy8\test_solution.py", line 7, in test_install
    self.assertEqual(parse_wantedby(text), "multi-user.target")
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: None != 'multi-user.target'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `parse_wantedby(unit_text)` returning the WantedBy= value from an
`[Install]` section, or None. Last matching line wins. Ignore comments.

--- solution.py (buggy) ---
def parse_wantedby(unit_text):
 section = None
 wanted = None
 for raw in unit_text.splitlines():
 line = raw.split(";", 1)[0].split("#", 1)[0].strip()
 if not line:
 continue
 if line.startswith("[") and line.endswith("]"):
 section = line[1:-1]
 continue
 if section != "Install" and line.startswith("WantedBy="):
 wanted = line.split("=", 1)[1].strip()
 return wanted

--- test_solution.py ---
import unittest
from solution import parse_wantedby

class Test(unittest.TestCase):
 def test_install(self):
 text = "[Unit]\n[Install]\nWantedBy=multi-user.target\n"
 self.assertEqual(parse_wantedby(text), "multi-user.target")

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_install (test_solution.Test.test_install) ... FAIL

======================================================================
FAIL: test_install (test_solution.Test.test_install)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-xlarccy8\test_solution.py", line 7, in test_install
 self.assertEqual(parse_wantedby(text), "multi-user.target")
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: None != 'multi-user.target'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def parse_cpu(value):
 if value.endswith("m") and value[:-1].isdigit():
 return int(value[:-1]) / 1000.0
 if value.replace(".", "", 1).isdigit():
 return float(value)
 raise ValueError(value)

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def parse_cpu(value):
    if value.endswith("m") and value[:-1].isdigit():
        return int(value[:-1]) / 1000.0
    if value.replace(".", "", 1).isdigit():
        return float(value)
    raise ValueError(value)

import unittest
from solution import parse_cpu

class Test(unittest.TestCase):
    def test_cpu(self):
        self.assertEqual(parse_cpu("100m"), 0.1)
        self.assertEqual(parse_cpu("2"), 2.0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_cpu(value)` converting Kubernetes CPU strings: `100m` -> 0.1,
`2` -> 2.0. Raise ValueError otherwise.


Answer:
class Ring:
 def __init__(self, n):
 if n < 1:
 raise ValueError("n")
 self.buf = [None] * n
 self.n = n
 self.i = 0
 self.size = 0

 def push(self, x):
 self.buf[self.i] = x
 self.i = (self.i + 1) % self.n
 self.size = min(self.size + 1, self.n)

 def snapshot(self):
 start = (self.i - self.size) % self.n
 return [self.buf[(start + k) % self.n] for k in range(self.size)]

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

class Ring:
    def __init__(self, n):
        if n < 1:
            raise ValueError("n")
        self.buf = [None] * n
        self.n = n
        self.i = 0
        self.size = 0

    def push(self, x):
        self.buf[self.i] = x
        self.i = (self.i + 1) % self.n
        self.size = min(self.size + 1, self.n)

    def snapshot(self):
        start = (self.i - self.size) % self.n
        return [self.buf[(start + k) % self.n] for k in range(self.size)]

import unittest
from solution import Ring

class Test(unittest.TestCase):
    def test_wrap(self):
        r = Ring(3)
        for x in range(5):
            r.push(x)
        self.assertEqual(r.snapshot(), [2, 3, 4])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `Ring(n)` with `push(x)` (overwrite oldest when full) and
`snapshot()` returning items oldest-to-newest.


Answer:
class Ring:
 def __init__(self, n):
 if n < 1:
 raise ValueError("n")
 self.buf = [None] * n
 self.n = n
 self.i = 0
 self.size = 0

 def push(self, x):
 self.buf[self.i] = x
 self.i = (self.i + 1) % self.n
 self.size = min(self.size + 1, self.n)

 def snapshot(self):
 start = (self.i - self.size) % self.n
 return [self.buf[(start + k) % self.n] for k in range(self.size)]

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_wrap (test_solution.Test.test_wrap) ... FAIL

======================================================================
FAIL: test_wrap (test_solution.Test.test_wrap)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-byeo4lnf\test_solution.py", line 9, in test_wrap
    self.assertEqual(r.snapshot(), [2, 3, 4])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [2, 4, 3] != [2, 3, 4]

First differing element 1:
4
3

- [2, 4, 3]
+ [2, 3, 4]

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `Ring(n)` with `push(x)` (overwrite oldest when full) and
`snapshot()` returning items oldest-to-newest.

--- solution.py (buggy) ---
class Ring:
 def __init__(self, n):
 if n < 1:
 raise ValueError("n")
 self.buf = [None] * n
 self.n = n
 self.i = 0
 self.size = 0

 def push(self, x):
 self.buf[self.i] = x
 self.i = (self.i - 1) % self.n
 self.size = min(self.size + 1, self.n)

 def snapshot(self):
 start = (self.i - self.size) % self.n
 return [self.buf[(start + k) % self.n] for k in range(self.size)]

--- test_solution.py ---
import unittest
from solution import Ring

class Test(unittest.TestCase):
 def test_wrap(self):
 r = Ring(3)
 for x in range(5):
 r.push(x)
 self.assertEqual(r.snapshot(), [2, 3, 4])

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_wrap (test_solution.Test.test_wrap) ... FAIL

======================================================================
FAIL: test_wrap (test_solution.Test.test_wrap)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-byeo4lnf\test_solution.py", line 9, in test_wrap
 self.assertEqual(r.snapshot(), [2, 3, 4])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [2, 4, 3] != [2, 3, 4]

First differing element 1:
4
3

- [2, 4, 3]
+ [2, 3, 4]

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)


Answer:
class UnionFind:
 def __init__(self, n):
 self.p = list(range(n))
 self.r = [0] * n

 def find(self, i):
 while self.p[i] != i:
 self.p[i] = self.p[self.p[i]]
 i = self.p[i]
 return i

 def union(self, i, j):
 a, b = self.find(i), self.find(j)
 if a == b:
 return False
 if self.r[a] < self.r[b]:
 a, b = b, a
 self.p[b] = a
 if self.r[a] == self.r[b]:
 self.r[a] += 1
 return True

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

class UnionFind:
    def __init__(self, n):
        self.p = list(range(n))
        self.r = [0] * n

    def find(self, i):
        while self.p[i] != i:
            self.p[i] = self.p[self.p[i]]
            i = self.p[i]
        return i

    def union(self, i, j):
        a, b = self.find(i), self.find(j)
        if a == b:
            return False
        if self.r[a] < self.r[b]:
            a, b = b, a
        self.p[b] = a
        if self.r[a] == self.r[b]:
            self.r[a] += 1
        return True

import unittest
from solution import UnionFind

class Test(unittest.TestCase):
    def test_uf(self):
        u = UnionFind(4)
        self.assertTrue(u.union(0, 1))
        self.assertTrue(u.union(2, 3))
        self.assertFalse(u.union(0, 1))
        self.assertEqual(u.find(0), u.find(1))
        self.assertNotEqual(u.find(0), u.find(2))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `UnionFind(n)` with 0..n-1 elements, `find(i)`, `union(i,j)`
returning True if they were in different sets. Use path compression and union by rank.


Answer:
class UnionFind:
 def __init__(self, n):
 self.p = list(range(n))
 self.r = [0] * n

 def find(self, i):
 while self.p[i] != i:
 self.p[i] = self.p[self.p[i]]
 i = self.p[i]
 return i

 def union(self, i, j):
 a, b = self.find(i), self.find(j)
 if a == b:
 return False
 if self.r[a] < self.r[b]:
 a, b = b, a
 self.p[b] = a
 if self.r[a] == self.r[b]:
 self.r[a] += 1
 return True

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_uf (test_solution.Test.test_uf) ... FAIL

======================================================================
FAIL: test_uf (test_solution.Test.test_uf)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-06_ablgo\test_solution.py", line 7, in test_uf
    self.assertTrue(u.union(0, 1))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `UnionFind(n)` with 0..n-1 elements, `find(i)`, `union(i,j)`
returning True if they were in different sets. Use path compression and union by rank.

--- solution.py (buggy) ---
class UnionFind:
 def __init__(self, n):
 self.p = list(range(n))
 self.r = [0] * n

 def find(self, i):
 while self.p[i] != i:
 self.p[i] = self.p[self.p[i]]
 i = self.p[i]
 return i

 def union(self, i, j):
 a, b = self.find(i), self.find(j)
 if a == b:
 return False
 if self.r[a] < self.r[b]:
 a, b = b, a
 self.p[b] = a
 if self.r[a] == self.r[b]:
 self.r[a] += 1
 return False

--- test_solution.py ---
import unittest
from solution import UnionFind

class Test(unittest.TestCase):
 def test_uf(self):
 u = UnionFind(4)
 self.assertTrue(u.union(0, 1))
 self.assertTrue(u.union(2, 3))
 self.assertFalse(u.union(0, 1))
 self.assertEqual(u.find(0), u.find(1))
 self.assertNotEqual(u.find(0), u.find(2))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_uf (test_solution.Test.test_uf) ... FAIL

======================================================================
FAIL: test_uf (test_solution.Test.test_uf)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-06_ablgo\test_solution.py", line 7, in test_uf
 self.assertTrue(u.union(0, 1))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def knapsack(weights, values, cap):
 dp = [0] * (cap + 1)
 for w, v in zip(weights, values):
 for c in range(cap, w - 1, -1):
 dp[c] = max(dp[c], dp[c - w] + v)
 return dp[cap]

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def knapsack(weights, values, cap):
    dp = [0] * (cap + 1)
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[cap]

import unittest
from solution import knapsack

class Test(unittest.TestCase):
    def test_ks(self):
        self.assertEqual(knapsack([2, 3, 4], [3, 4, 5], 5), 7)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `knapsack(weights, values, cap)` 0/1 knapsack maximum value.


Answer:
def knapsack(weights, values, cap):
 dp = [0] * (cap + 1)
 for w, v in zip(weights, values):
 for c in range(cap, w - 1, -1):
 dp[c] = max(dp[c], dp[c - w] + v)
 return dp[cap]

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_ks (test_solution.Test.test_ks) ... ERROR

======================================================================
ERROR: test_ks (test_solution.Test.test_ks)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ho4m81vl\test_solution.py", line 6, in test_ks
    self.assertEqual(knapsack([2, 3, 4], [3, 4, 5], 5), 7)
                     ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ho4m81vl\solution.py", line 5, in knapsack
    dp[c] = max(dp[c], dp[c - w] + v)
                ~~^^^
IndexError: list index out of range

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `knapsack(weights, values, cap)` 0/1 knapsack maximum value.

--- solution.py (buggy) ---
def knapsack(weights, values, cap):
 dp = [0] * (cap - 1)
 for w, v in zip(weights, values):
 for c in range(cap, w - 1, -1):
 dp[c] = max(dp[c], dp[c - w] + v)
 return dp[cap]

--- test_solution.py ---
import unittest
from solution import knapsack

class Test(unittest.TestCase):
 def test_ks(self):
 self.assertEqual(knapsack([2, 3, 4], [3, 4, 5], 5), 7)

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_ks (test_solution.Test.test_ks) ... ERROR

======================================================================
ERROR: test_ks (test_solution.Test.test_ks)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ho4m81vl\test_solution.py", line 6, in test_ks
 self.assertEqual(knapsack([2, 3, 4], [3, 4, 5], 5), 7)
 ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ho4m81vl\solution.py", line 5, in knapsack
 dp[c] = max(dp[c], dp[c - w] + v)
 ~~^^^
IndexError: list index out of range

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)


Answer:
from collections import deque

def bfs_order(graph, start):
 seen = {start}
 q = deque([start])
 order = []
 while q:
 node = q.popleft()
 order.append(node)
 for nxt in graph.get(node, []):
 if nxt not in seen:
 seen.add(nxt)
 q.append(nxt)
 return order

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

from collections import deque

def bfs_order(graph, start):
    seen = {start}
    q = deque([start])
    order = []
    while q:
        node = q.popleft()
        order.append(node)
        for nxt in graph.get(node, []):
            if nxt not in seen:
                seen.add(nxt)
                q.append(nxt)
    return order

import unittest
from solution import bfs_order

class Test(unittest.TestCase):
    def test_bfs(self):
        g = {1: [2, 3], 2: [4], 3: [], 4: []}
        self.assertEqual(bfs_order(g, 1), [1, 2, 3, 4])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `bfs_order(graph, start)` returning nodes in BFS order. graph maps
node -> iterable of neighbors. Skip missing neighbor keys.


Answer:
def covered_length(ranges):
 if not ranges:
 return 0
 ordered = sorted(ranges)
 total = 0
 cs, ce = ordered[0]
 for s, e in ordered[1:]:
 if s > ce:
 total += ce - cs
 cs, ce = s, e
 else:
 ce = max(ce, e)
 total += ce - cs
 return total

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def covered_length(ranges):
    if not ranges:
        return 0
    ordered = sorted(ranges)
    total = 0
    cs, ce = ordered[0]
    for s, e in ordered[1:]:
        if s > ce:
            total += ce - cs
            cs, ce = s, e
        else:
            ce = max(ce, e)
    total += ce - cs
    return total

import unittest
from solution import covered_length

class Test(unittest.TestCase):
    def test_cover(self):
        self.assertEqual(covered_length([(0, 3), (2, 5), (10, 12)]), 7)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `covered_length(ranges)` total length covered by [start,end]
half-open intervals. Overlaps count once.


Answer:
from collections import deque

class SlidingWindow:
 def __init__(self, limit, window):
 self.limit = limit
 self.window = window
 self.q = deque()

 def allow(self, t):
 while self.q and self.q[0] <= t - self.window:
 self.q.popleft()
 if len(self.q) >= self.limit:
 return False
 self.q.append(t)
 return True

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

from collections import deque

class SlidingWindow:
    def __init__(self, limit, window):
        self.limit = limit
        self.window = window
        self.q = deque()

    def allow(self, t):
        while self.q and self.q[0] <= t - self.window:
            self.q.popleft()
        if len(self.q) >= self.limit:
            return False
        self.q.append(t)
        return True

import unittest
from solution import SlidingWindow

class Test(unittest.TestCase):
    def test_sw(self):
        s = SlidingWindow(2, 10)
        self.assertTrue(s.allow(0))
        self.assertTrue(s.allow(1))
        self.assertFalse(s.allow(2))
        self.assertTrue(s.allow(11))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `SlidingWindow(limit, window)` with `allow(t)` where t is
non-decreasing time. At most `limit` events in (t-window, t].


Answer:
from collections import deque

class SlidingWindow:
 def __init__(self, limit, window):
 self.limit = limit
 self.window = window
 self.q = deque()

 def allow(self, t):
 while self.q and self.q[0] <= t - self.window:
 self.q.popleft()
 if len(self.q) >= self.limit:
 return False
 self.q.append(t)
 return True

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_sw (test_solution.Test.test_sw) ... FAIL

======================================================================
FAIL: test_sw (test_solution.Test.test_sw)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-i_lvhlh9\test_solution.py", line 7, in test_sw
    self.assertTrue(s.allow(0))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `SlidingWindow(limit, window)` with `allow(t)` where t is
non-decreasing time. At most `limit` events in (t-window, t].

--- solution.py (buggy) ---
from collections import deque

class SlidingWindow:
 def __init__(self, limit, window):
 self.limit = limit
 self.window = window
 self.q = deque()

 def allow(self, t):
 while self.q and self.q[0] <= t - self.window:
 self.q.popleft()
 if len(self.q) >= self.limit:
 return False
 self.q.append(t)
 return False

--- test_solution.py ---
import unittest
from solution import SlidingWindow

class Test(unittest.TestCase):
 def test_sw(self):
 s = SlidingWindow(2, 10)
 self.assertTrue(s.allow(0))
 self.assertTrue(s.allow(1))
 self.assertFalse(s.allow(2))
 self.assertTrue(s.allow(11))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_sw (test_solution.Test.test_sw) ... FAIL

======================================================================
FAIL: test_sw (test_solution.Test.test_sw)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-i_lvhlh9\test_solution.py", line 7, in test_sw
 self.assertTrue(s.allow(0))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
def b64_pad(s):
 m = len(s) % 4
 if m == 1:
 raise ValueError("invalid")
 if m:
 s += "=" * (4 - m)
 return s

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def b64_pad(s):
    m = len(s) % 4
    if m == 1:
        raise ValueError("invalid")
    if m:
        s += "=" * (4 - m)
    return s

import unittest
from solution import b64_pad

class Test(unittest.TestCase):
    def test_pad(self):
        self.assertEqual(b64_pad("TQ"), "TQ==")
        self.assertEqual(b64_pad("TWE"), "TWE=")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `b64_pad(s)` adding the correct `=` padding to a base64 string
without padding. Do not decode.


Answer:
def b64_pad(s):
 m = len(s) % 4
 if m == 1:
 raise ValueError("invalid")
 if m:
 s += "=" * (4 - m)
 return s

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_pad (test_solution.Test.test_pad) ... ERROR

======================================================================
ERROR: test_pad (test_solution.Test.test_pad)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4jfmh1lq\test_solution.py", line 6, in test_pad
    self.assertEqual(b64_pad("TQ"), "TQ==")
                     ~~~~~~~^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4jfmh1lq\solution.py", line 4, in b64_pad
    raise ValueError("invalid")
ValueError: invalid

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `b64_pad(s)` adding the correct `=` padding to a base64 string
without padding. Do not decode.

--- solution.py (buggy) ---
def b64_pad(s):
 m = len(s) % 4
 if m != 1:
 raise ValueError("invalid")
 if m:
 s += "=" * (4 - m)
 return s

--- test_solution.py ---
import unittest
from solution import b64_pad

class Test(unittest.TestCase):
 def test_pad(self):
 self.assertEqual(b64_pad("TQ"), "TQ==")
 self.assertEqual(b64_pad("TWE"), "TWE=")

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_pad (test_solution.Test.test_pad) ... ERROR

======================================================================
ERROR: test_pad (test_solution.Test.test_pad)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4jfmh1lq\test_solution.py", line 6, in test_pad
 self.assertEqual(b64_pad("TQ"), "TQ==")
 ~~~~~~~^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4jfmh1lq\solution.py", line 4, in b64_pad
 raise ValueError("invalid")
ValueError: invalid

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)


Answer:
def retry(fn, retries, retry_on):
 last = None
 for _ in range(retries + 1):
 try:
 return fn()
 except retry_on as exc:
 last = exc
 raise last

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def retry(fn, retries, retry_on):
    last = None
    for _ in range(retries + 1):
        try:
            return fn()
        except retry_on as exc:
            last = exc
    raise last

import unittest
from solution import retry

class Test(unittest.TestCase):
    def test_retry(self):
        n = {"c": 0}
        def f():
            n["c"] += 1
            if n["c"] < 3:
                raise ValueError("x")
            return 7
        self.assertEqual(retry(f, 5, ValueError), 7)
        self.assertEqual(n["c"], 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `retry(fn, retries, retry_on)` calling fn until it returns without
raising an exception in retry_on, up to retries+1 attempts. Re-raise the last.


Answer:
def parse_ini(text):
 data = {}
 section = None
 for raw in text.splitlines():
 line = raw.split(";", 1)[0].strip()
 if not line:
 continue
 if line.startswith("[") and line.endswith("]"):
 section = line[1:-1]
 data.setdefault(section, {})
 continue
 if section is None or "=" not in line:
 raise ValueError(line)
 k, v = line.split("=", 1)
 data[section][k.strip()] = v.strip()
 return data

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def parse_ini(text):
    data = {}
    section = None
    for raw in text.splitlines():
        line = raw.split(";", 1)[0].strip()
        if not line:
            continue
        if line.startswith("[") and line.endswith("]"):
            section = line[1:-1]
            data.setdefault(section, {})
            continue
        if section is None or "=" not in line:
            raise ValueError(line)
        k, v = line.split("=", 1)
        data[section][k.strip()] = v.strip()
    return data

import unittest
from solution import parse_ini

class Test(unittest.TestCase):
    def test_ini(self):
        text = "[db]\nhost=localhost\n; c\nport=1\n"
        self.assertEqual(parse_ini(text), {"db": {"host": "localhost", "port": "1"}})

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_ini(text)` returning dict[str, dict[str, str]] for
`[section]` and `key=value` lines. Ignore blanks and `;` comments.


Answer:
from collections import defaultdict, deque

def longest_path_dag(nodes, edges, weight):
 graph = defaultdict(list)
 indeg = {n: 0 for n in nodes}
 for u, v in edges:
 graph[u].append(v)
 indeg[v] += 1
 dist = {n: 0 for n in nodes}
 q = deque([n for n in nodes if indeg[n] == 0])
 seen = 0
 while q:
 u = q.popleft()
 seen += 1
 for v in graph[u]:
 dist[v] = max(dist[v], dist[u] + weight[(u, v)])
 indeg[v] -= 1
 if indeg[v] == 0:
 q.append(v)
 if seen != len(nodes):
 raise ValueError("not a dag")
 return max(dist.values())

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

from collections import defaultdict, deque

def longest_path_dag(nodes, edges, weight):
    graph = defaultdict(list)
    indeg = {n: 0 for n in nodes}
    for u, v in edges:
        graph[u].append(v)
        indeg[v] += 1
    dist = {n: 0 for n in nodes}
    q = deque([n for n in nodes if indeg[n] == 0])
    seen = 0
    while q:
        u = q.popleft()
        seen += 1
        for v in graph[u]:
            dist[v] = max(dist[v], dist[u] + weight[(u, v)])
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    if seen != len(nodes):
        raise ValueError("not a dag")
    return max(dist.values())

import unittest
from solution import longest_path_dag

class Test(unittest.TestCase):
    def test_lp(self):
        w = {("a", "b"): 2, ("b", "c"): 3, ("a", "c"): 4}
        self.assertEqual(longest_path_dag(["a", "b", "c"], [("a", "b"), ("b", "c"), ("a", "c")], w), 5)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `longest_path_dag(nodes, edges, weight)` where edges are (u,v)
and weight[(u,v)] is a number. Graph is DAG. Return the maximum path weight
(possibly a single node path of weight 0).


Answer:
from collections import defaultdict, deque

def longest_path_dag(nodes, edges, weight):
 graph = defaultdict(list)
 indeg = {n: 0 for n in nodes}
 for u, v in edges:
 graph[u].append(v)
 indeg[v] += 1
 dist = {n: 0 for n in nodes}
 q = deque([n for n in nodes if indeg[n] == 0])
 seen = 0
 while q:
 u = q.popleft()
 seen += 1
 for v in graph[u]:
 dist[v] = max(dist[v], dist[u] + weight[(u, v)])
 indeg[v] -= 1
 if indeg[v] == 0:
 q.append(v)
 if seen != len(nodes):
 raise ValueError("not a dag")
 return max(dist.values())

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_lp (test_solution.Test.test_lp) ... ERROR

======================================================================
ERROR: test_lp (test_solution.Test.test_lp)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-c11ranue\test_solution.py", line 7, in test_lp
    self.assertEqual(longest_path_dag(["a", "b", "c"], [("a", "b"), ("b", "c"), ("a", "c")], w), 5)
                     ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-c11ranue\solution.py", line 21, in longest_path_dag
    raise ValueError("not a dag")
ValueError: not a dag

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `longest_path_dag(nodes, edges, weight)` where edges are (u,v)
and weight[(u,v)] is a number. Graph is DAG. Return the maximum path weight
(possibly a single node path of weight 0).

--- solution.py (buggy) ---
from collections import defaultdict, deque

def longest_path_dag(nodes, edges, weight):
 graph = defaultdict(list)
 indeg = {n: 0 for n in nodes}
 for u, v in edges:
 graph[u].append(v)
 indeg[v] += 1
 dist = {n: 0 for n in nodes}
 q = deque([n for n in nodes if indeg[n] != 0])
 seen = 0
 while q:
 u = q.popleft()
 seen += 1
 for v in graph[u]:
 dist[v] = max(dist[v], dist[u] + weight[(u, v)])
 indeg[v] -= 1
 if indeg[v] == 0:
 q.append(v)
 if seen != len(nodes):
 raise ValueError("not a dag")
 return max(dist.values())

--- test_solution.py ---
import unittest
from solution import longest_path_dag

class Test(unittest.TestCase):
 def test_lp(self):
 w = {("a", "b"): 2, ("b", "c"): 3, ("a", "c"): 4}
 self.assertEqual(longest_path_dag(["a", "b", "c"], [("a", "b"), ("b", "c"), ("a", "c")], w), 5)

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 0, "errors": 1, "skipped": 0, "passed": false}

test_lp (test_solution.Test.test_lp) ... ERROR

======================================================================
ERROR: test_lp (test_solution.Test.test_lp)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-c11ranue\test_solution.py", line 7, in test_lp
 self.assertEqual(longest_path_dag(["a", "b", "c"], [("a", "b"), ("b", "c"), ("a", "c")], w), 5)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-c11ranue\solution.py", line 21, in longest_path_dag
 raise ValueError("not a dag")
ValueError: not a dag

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)


Answer:
import heapq

def k_smallest(nums, k):
 if k <= 0:
 return []
 return sorted(heapq.nsmallest(min(k, len(nums)), nums))

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

import heapq

def k_smallest(nums, k):
    if k <= 0:
        return []
    return sorted(heapq.nsmallest(min(k, len(nums)), nums))

import unittest
from solution import k_smallest

class Test(unittest.TestCase):
    def test_k(self):
        self.assertEqual(k_smallest([5, 1, 4, 2], 2), [1, 2])
        self.assertEqual(k_smallest([3], 5), [3])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `k_smallest(nums, k)` returning the k smallest values sorted
ascending. k may be 0. If k > n, return all sorted.


Answer:
from itertools import zip_longest

def constant_eq(a, b):
 diff = 0
 for x, y in zip_longest(a, b, fillvalue=None):
 diff |= (x != y)
 return not diff

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

from itertools import zip_longest

def constant_eq(a, b):
    diff = 0
    for x, y in zip_longest(a, b, fillvalue=None):
        diff |= (x != y)
    return not diff

import unittest
from solution import constant_eq

class Test(unittest.TestCase):
    def test_eq(self):
        self.assertTrue(constant_eq("abc", "abc"))
        self.assertFalse(constant_eq("abc", "ab"))
        self.assertFalse(constant_eq("abc", "abd"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `constant_eq(a, b)` comparing two strings in time that depends
only on the length of the longer input (iterate zip_longest). Return True iff equal.


Answer:
from itertools import zip_longest

def constant_eq(a, b):
 diff = 0
 for x, y in zip_longest(a, b, fillvalue=None):
 diff |= (x != y)
 return not diff

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_eq (test_solution.Test.test_eq) ... FAIL

======================================================================
FAIL: test_eq (test_solution.Test.test_eq)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-zk_iybqw\test_solution.py", line 6, in test_eq
    self.assertTrue(constant_eq("abc", "abc"))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `constant_eq(a, b)` comparing two strings in time that depends
only on the length of the longer input (iterate zip_longest). Return True iff equal.

--- solution.py (buggy) ---
from itertools import zip_longest

def constant_eq(a, b):
 diff = 0
 for x, y in zip_longest(a, b, fillvalue=None):
 diff |= (x != y)
 return diff

--- test_solution.py ---
import unittest
from solution import constant_eq

class Test(unittest.TestCase):
 def test_eq(self):
 self.assertTrue(constant_eq("abc", "abc"))
 self.assertFalse(constant_eq("abc", "ab"))
 self.assertFalse(constant_eq("abc", "abd"))

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_eq (test_solution.Test.test_eq) ... FAIL

======================================================================
FAIL: test_eq (test_solution.Test.test_eq)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-zk_iybqw\test_solution.py", line 6, in test_eq
 self.assertTrue(constant_eq("abc", "abc"))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


Answer:
ORDER = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3}

def filter_logs(lines, min_level):
 threshold = ORDER[min_level]
 out = []
 for line in lines:
 lvl = line.split(" ", 1)[0]
 if ORDER.get(lvl, -1) >= threshold:
 out.append(line)
 return out

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

ORDER = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3}

def filter_logs(lines, min_level):
    threshold = ORDER[min_level]
    out = []
    for line in lines:
        lvl = line.split(" ", 1)[0]
        if ORDER.get(lvl, -1) >= threshold:
            out.append(line)
    return out

import unittest
from solution import filter_logs

class Test(unittest.TestCase):
    def test_filter(self):
        lines = ["DEBUG x", "INFO y", "ERROR z"]
        self.assertEqual(filter_logs(lines, "INFO"), ["INFO y", "ERROR z"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `filter_logs(lines, min_level)` where each line starts with
DEBUG|INFO|WARN|ERROR. Levels increase in that order. Keep lines at or above min_level.


Answer:
ORDER = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3}

def filter_logs(lines, min_level):
 threshold = ORDER[min_level]
 out = []
 for line in lines:
 lvl = line.split(" ", 1)[0]
 if ORDER.get(lvl, -1) >= threshold:
 out.append(line)
 return out

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_filter (test_solution.Test.test_filter) ... FAIL

======================================================================
FAIL: test_filter (test_solution.Test.test_filter)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-y0tloy1c\test_solution.py", line 7, in test_filter
    self.assertEqual(filter_logs(lines, "INFO"), ["INFO y", "ERROR z"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['ERROR z'] != ['INFO y', 'ERROR z']

First differing element 0:
'ERROR z'
'INFO y'

Second list contains 1 additional elements.
First extra element 1:
'ERROR z'

- ['ERROR z']
+ ['INFO y', 'ERROR z']

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `filter_logs(lines, min_level)` where each line starts with
DEBUG|INFO|WARN|ERROR. Levels increase in that order. Keep lines at or above min_level.

--- solution.py (buggy) ---
ORDER = {"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3}

def filter_logs(lines, min_level):
 threshold = ORDER[min_level]
 out = []
 for line in lines:
 lvl = line.split(" ", 1)[0]
 if ORDER.get(lvl, -1) > threshold:
 out.append(line)
 return out

--- test_solution.py ---
import unittest
from solution import filter_logs

class Test(unittest.TestCase):
 def test_filter(self):
 lines = ["DEBUG x", "INFO y", "ERROR z"]
 self.assertEqual(filter_logs(lines, "INFO"), ["INFO y", "ERROR z"])

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_filter (test_solution.Test.test_filter) ... FAIL

======================================================================
FAIL: test_filter (test_solution.Test.test_filter)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-y0tloy1c\test_solution.py", line 7, in test_filter
 self.assertEqual(filter_logs(lines, "INFO"), ["INFO y", "ERROR z"])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['ERROR z'] != ['INFO y', 'ERROR z']

First differing element 0:
'ERROR z'
'INFO y'

Second list contains 1 additional elements.
First extra element 1:
'ERROR z'

- ['ERROR z']
+ ['INFO y', 'ERROR z']

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)


Answer:
def matmul(a, b):
 if not a or not b or len(a[0]) != len(b):
 raise ValueError("shape")
 cols = len(b[0])
 out = []
 for row in a:
 out.append([sum(row[k] * b[k][j] for k in range(len(b))) for j in range(cols)])
 return out

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def matmul(a, b):
    if not a or not b or len(a[0]) != len(b):
        raise ValueError("shape")
    cols = len(b[0])
    out = []
    for row in a:
        out.append([sum(row[k] * b[k][j] for k in range(len(b))) for j in range(cols)])
    return out

import unittest
from solution import matmul

class Test(unittest.TestCase):
    def test_mul(self):
        self.assertEqual(matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]), [[19, 22], [43, 50]])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `matmul(a, b)` for lists of lists of numbers. Raise ValueError
on shape mismatch.


Answer:
def char_freq(text):
 out = {}
 for ch in text:
 out[ch] = out.get(ch, 0) + 1
 return out

Use only the Python standard library unless the prompt says otherwise.

The hidden tests in test_solution.py must pass.

def char_freq(text):
    out = {}
    for ch in text:
        out[ch] = out.get(ch, 0) + 1
    return out

import unittest
from solution import char_freq

class Test(unittest.TestCase):
    def test_freq(self):
        self.assertEqual(char_freq("aba"), {"a": 2, "b": 1})

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `char_freq(text)` returning a dict of character -> count,
omitting zeros. Empty string yields {}.


Answer:
def char_freq(text):
 out = {}
 for ch in text:
 out[ch] = out.get(ch, 0) + 1
 return out

Do not weaken or delete tests
Keep the public API

Output:
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_freq (test_solution.Test.test_freq) ... FAIL

======================================================================
FAIL: test_freq (test_solution.Test.test_freq)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4pi401pu\test_solution.py", line 6, in test_freq
    self.assertEqual(char_freq("aba"), {"a": 2, "b": 1})
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'a': -2, 'b': -1} != {'a': 2, 'b': 1}
- {'a': -2, 'b': -1}
?       -        -

+ {'a': 2, 'b': 1}

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Seeded mutation of the reference implementation.

Reproduce the failure
Identify the defect
Apply a minimal fix
Re-run tests

Prompt:
The following Python module fails its tests. Produce a corrected solution.py that preserves the intended behaviour.

Implement `char_freq(text)` returning a dict of character -> count,
omitting zeros. Empty string yields {}.

--- solution.py (buggy) ---
def char_freq(text):
 out = {}
 for ch in text:
 out[ch] = out.get(ch, 0) - 1
 return out

--- test_solution.py ---
import unittest
from solution import char_freq

class Test(unittest.TestCase):
 def test_freq(self):
 self.assertEqual(char_freq("aba"), {"a": 2, "b": 1})

--- failure ---
OPEN_REASON_RESULT {"tests_run": 1, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_freq (test_solution.Test.test_freq) ... FAIL

======================================================================
FAIL: test_freq (test_solution.Test.test_freq)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4pi401pu\test_solution.py", line 6, in test_freq
 self.assertEqual(char_freq("aba"), {"a": 2, "b": 1})
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'a': -2, 'b': -1} != {'a': 2, 'b': 1}
- {'a': -2, 'b': -1}
? - -

+ {'a': 2, 'b': 1}

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)