Answer:
def delimiters_ok(text):
 pairs = {")": "(", "]": "[", "}": "{"}
 stack = []
 for ch in text:
 if ch in "([{":
 stack.append(ch)
 elif ch in ")]}":
 if not stack or stack[-1] != pairs[ch]:
 return False
 stack.pop()
 return not stack

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

The hidden tests in test_solution.py must pass.

def delimiters_ok(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
    return not stack

import unittest
from solution import delimiters_ok

class Test(unittest.TestCase):
    def test_mixed(self):
        self.assertTrue(delimiters_ok("fn(a[i], {x: 1})"))
    def test_crossed(self):
        self.assertFalse(delimiters_ok("([)]"))
    def test_extra_close(self):
        self.assertFalse(delimiters_ok("ok)"))
    def test_ignore_other(self):
        self.assertTrue(delimiters_ok(""))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `delimiters_ok(text: str) -> bool`.

Return True if every round, square, and curly bracket in `text` is correctly
nested and matched. All other characters are ignored. Empty input is valid.

test_crossed (test_solution.Test.test_crossed) ... ok
test_extra_close (test_solution.Test.test_extra_close) ... ok
test_ignore_other (test_solution.Test.test_ignore_other) ... ok
test_mixed (test_solution.Test.test_mixed) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

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


Answer:
def max_window_sum(values, k):
 if k <= 0 or k > len(values):
 raise ValueError("invalid window")
 current = sum(values[:k])
 best = current
 for i in range(k, len(values)):
 current += values[i] - values[i - k]
 if current > best:
 best = current
 return best

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

The hidden tests in test_solution.py must pass.

def max_window_sum(values, k):
    if k <= 0 or k > len(values):
        raise ValueError("invalid window")
    current = sum(values[:k])
    best = current
    for i in range(k, len(values)):
        current += values[i] - values[i - k]
        if current > best:
            best = current
    return best

import unittest
from solution import max_window_sum

class Test(unittest.TestCase):
    def test_example(self):
        self.assertEqual(max_window_sum([2, 1, 5, 1, 3, 2], 3), 9)
    def test_k_one(self):
        self.assertEqual(max_window_sum([-4, 8, -1], 1), 8)
    def test_bad(self):
        with self.assertRaises(ValueError):
            max_window_sum([1, 2], 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `max_window_sum(values, k)` returning the maximum sum of any
contiguous subarray of length `k`. If `k` is larger than the list, raise ValueError.

test_bad (test_solution.Test.test_bad) ... ok
test_example (test_solution.Test.test_example) ... ok
test_k_one (test_solution.Test.test_k_one) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

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


Answer:
def max_window_sum(values, k):
 if k <= 0 or k > len(values):
 raise ValueError("invalid window")
 current = sum(values[:k])
 best = current
 for i in range(k, len(values)):
 current += values[i] - values[i - k]
 if current > best:
 best = current
 return best

Do not weaken or delete tests
Keep the public API

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

test_bad (test_solution.Test.test_bad) ... ok
test_example (test_solution.Test.test_example) ... FAIL
test_k_one (test_solution.Test.test_k_one) ... FAIL

======================================================================
FAIL: test_example (test_solution.Test.test_example)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-vb8pc209\test_solution.py", line 6, in test_example
    self.assertEqual(max_window_sum([2, 1, 5, 1, 3, 2], 3), 9)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 14 != 9

======================================================================
FAIL: test_k_one (test_solution.Test.test_k_one)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-vb8pc209\test_solution.py", line 8, in test_k_one
    self.assertEqual(max_window_sum([-4, 8, -1], 1), 8)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 4 != 8

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=2)

Forgets to subtract the value leaving the window.

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 `max_window_sum(values, k)` returning the maximum sum of any
contiguous subarray of length `k`. If `k` is larger than the list, raise ValueError.

--- solution.py (buggy) ---
def max_window_sum(values, k):
 if k <= 0 or k > len(values):
 raise ValueError("invalid window")
 current = sum(values[:k])
 best = current
 for i in range(k, len(values)):
 current += values[i]
 if current > best:
 best = current
 return best

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

class Test(unittest.TestCase):
 def test_example(self):
 self.assertEqual(max_window_sum([2, 1, 5, 1, 3, 2], 3), 9)
 def test_k_one(self):
 self.assertEqual(max_window_sum([-4, 8, -1], 1), 8)
 def test_bad(self):
 with self.assertRaises(ValueError):
 max_window_sum([1, 2], 3)

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

test_bad (test_solution.Test.test_bad) ... ok
test_example (test_solution.Test.test_example) ... FAIL
test_k_one (test_solution.Test.test_k_one) ... FAIL

======================================================================
FAIL: test_example (test_solution.Test.test_example)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-vb8pc209\test_solution.py", line 6, in test_example
 self.assertEqual(max_window_sum([2, 1, 5, 1, 3, 2], 3), 9)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 14 != 9

======================================================================
FAIL: test_k_one (test_solution.Test.test_k_one)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-vb8pc209\test_solution.py", line 8, in test_k_one
 self.assertEqual(max_window_sum([-4, 8, -1], 1), 8)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 4 != 8

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=2)


Answer:
def group_in_order(items, key_fn):
 order = []
 buckets = {}
 for item in items:
 key = key_fn(item)
 if key not in buckets:
 buckets[key] = []
 order.append(key)
 buckets[key].append(item)
 return [(key, buckets[key]) for key in order]

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

The hidden tests in test_solution.py must pass.

def group_in_order(items, key_fn):
    order = []
    buckets = {}
    for item in items:
        key = key_fn(item)
        if key not in buckets:
            buckets[key] = []
            order.append(key)
        buckets[key].append(item)
    return [(key, buckets[key]) for key in order]

import unittest
from solution import group_in_order

class Test(unittest.TestCase):
    def test_order(self):
        data = ["apple", "apricot", "banana", "avocado"]
        got = group_in_order(data, lambda s: s[0])
        self.assertEqual([k for k, _ in got], ["a", "b"])
        self.assertEqual(got[0][1], ["apple", "apricot", "avocado"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `group_in_order(items, key_fn)` that groups consecutive items with
the same key, preserving first-seen group order for non-consecutive keys as well
(like an insertion-ordered map of lists). Return a list of (key, group_list) pairs.

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


Answer:
from collections import OrderedDict

class TinyLRU:
 def __init__(self, capacity):
 if capacity < 1:
 raise ValueError("capacity")
 self.capacity = capacity
 self._data = OrderedDict()

 def get(self, key):
 if key not in self._data:
 return None
 self._data.move_to_end(key)
 return self._data[key]

 def put(self, key, value):
 if key in self._data:
 self._data.move_to_end(key)
 self._data[key] = value
 else:
 self._data[key] = value
 if len(self._data) > self.capacity:
 self._data.popitem(last=False)

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

The hidden tests in test_solution.py must pass.

from collections import OrderedDict

class TinyLRU:
    def __init__(self, capacity):
        if capacity < 1:
            raise ValueError("capacity")
        self.capacity = capacity
        self._data = OrderedDict()

    def get(self, key):
        if key not in self._data:
            return None
        self._data.move_to_end(key)
        return self._data[key]

    def put(self, key, value):
        if key in self._data:
            self._data.move_to_end(key)
            self._data[key] = value
        else:
            self._data[key] = value
            if len(self._data) > self.capacity:
                self._data.popitem(last=False)

import unittest
from solution import TinyLRU

class Test(unittest.TestCase):
    def test_evict(self):
        c = TinyLRU(2)
        c.put("a", 1)
        c.put("b", 2)
        c.get("a")
        c.put("c", 3)
        self.assertIsNone(c.get("b"))
        self.assertEqual(c.get("a"), 1)
        self.assertEqual(c.get("c"), 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement class `TinyLRU(capacity)` with `get(key)` (return None if missing)
and `put(key, value)`. Evict the least recently used entry when over capacity.
Both get and put count as use.


Answer:
from collections import OrderedDict

class TinyLRU:
 def __init__(self, capacity):
 if capacity < 1:
 raise ValueError("capacity")
 self.capacity = capacity
 self._data = OrderedDict()

 def get(self, key):
 if key not in self._data:
 return None
 self._data.move_to_end(key)
 return self._data[key]

 def put(self, key, value):
 if key in self._data:
 self._data.move_to_end(key)
 self._data[key] = value
 else:
 self._data[key] = value
 if len(self._data) > self.capacity:
 self._data.popitem(last=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_evict (test_solution.Test.test_evict) ... FAIL

======================================================================
FAIL: test_evict (test_solution.Test.test_evict)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-v9sxhjaz\test_solution.py", line 11, in test_evict
    self.assertIsNone(c.get("b"))
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: 2 is not None

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

FAILED (failures=1)

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 `TinyLRU(capacity)` with `get(key)` (return None if missing)
and `put(key, value)`. Evict the least recently used entry when over capacity.
Both get and put count as use.

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

class TinyLRU:
 def __init__(self, capacity):
 self.capacity = capacity
 self._data = OrderedDict()

 def get(self, key):
 return self._data.get(key)

 def put(self, key, value):
 self._data[key] = value
 if len(self._data) > self.capacity:
 self._data.popitem(last=False)

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

class Test(unittest.TestCase):
 def test_evict(self):
 c = TinyLRU(2)
 c.put("a", 1)
 c.put("b", 2)
 c.get("a")
 c.put("c", 3)
 self.assertIsNone(c.get("b"))
 self.assertEqual(c.get("a"), 1)
 self.assertEqual(c.get("c"), 3)

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

test_evict (test_solution.Test.test_evict) ... FAIL

======================================================================
FAIL: test_evict (test_solution.Test.test_evict)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-v9sxhjaz\test_solution.py", line 11, in test_evict
 self.assertIsNone(c.get("b"))
 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: 2 is not None

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

FAILED (failures=1)


Answer:
def first_ge(sorted_values, target):
 lo, hi = 0, len(sorted_values)
 while lo < hi:
 mid = (lo + hi) // 2
 if sorted_values[mid] < target:
 lo = mid + 1
 else:
 hi = mid
 return lo

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

The hidden tests in test_solution.py must pass.

def first_ge(sorted_values, target):
    lo, hi = 0, len(sorted_values)
    while lo < hi:
        mid = (lo + hi) // 2
        if sorted_values[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

import unittest
from solution import first_ge

class Test(unittest.TestCase):
    def test_mid(self):
        self.assertEqual(first_ge([1, 3, 3, 7, 9], 3), 1)
    def test_end(self):
        self.assertEqual(first_ge([1, 2, 4], 5), 3)
    def test_first(self):
        self.assertEqual(first_ge([2, 4, 6], 0), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `first_ge(sorted_values, target)` returning the smallest index i
such that sorted_values[i] >= target, or len(sorted_values) if none exists.
The list is sorted non-decreasing.

test_end (test_solution.Test.test_end) ... ok
test_first (test_solution.Test.test_first) ... ok
test_mid (test_solution.Test.test_mid) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK


Answer:
def merge_ranges(ranges):
 if not ranges:
 return []
 ordered = sorted(ranges, key=lambda r: r[0])
 out = [list(ordered[0])]
 for start, end in ordered[1:]:
 if start <= out[-1][1]:
 out[-1][1] = max(out[-1][1], end)
 else:
 out.append([start, end])
 return out

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

The hidden tests in test_solution.py must pass.

def merge_ranges(ranges):
    if not ranges:
        return []
    ordered = sorted(ranges, key=lambda r: r[0])
    out = [list(ordered[0])]
    for start, end in ordered[1:]:
        if start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out

import unittest
from solution import merge_ranges

class Test(unittest.TestCase):
    def test_overlap(self):
        self.assertEqual(merge_ranges([[1, 3], [2, 6], [8, 10]]), [[1, 6], [8, 10]])
    def test_touch(self):
        self.assertEqual(merge_ranges([[1, 2], [2, 3]]), [[1, 3]])
    def test_empty(self):
        self.assertEqual(merge_ranges([]), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `merge_ranges(ranges)` where each range is [start, end] with
start <= end. Return a new list of disjoint merged ranges sorted by start.

test_empty (test_solution.Test.test_empty) ... ok
test_overlap (test_solution.Test.test_overlap) ... ok
test_touch (test_solution.Test.test_touch) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK


Answer:
def merge_ranges(ranges):
 if not ranges:
 return []
 ordered = sorted(ranges, key=lambda r: r[0])
 out = [list(ordered[0])]
 for start, end in ordered[1:]:
 if start <= out[-1][1]:
 out[-1][1] = max(out[-1][1], end)
 else:
 out.append([start, end])
 return out

Do not weaken or delete tests
Keep the public API

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

test_empty (test_solution.Test.test_empty) ... ok
test_overlap (test_solution.Test.test_overlap) ... ok
test_touch (test_solution.Test.test_touch) ... FAIL

======================================================================
FAIL: test_touch (test_solution.Test.test_touch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ajewpy74\test_solution.py", line 8, in test_touch
    self.assertEqual(merge_ranges([[1, 2], [2, 3]]), [[1, 3]])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [[1, 2], [2, 3]] != [[1, 3]]

First differing element 0:
[1, 2]
[1, 3]

First list contains 1 additional elements.
First extra element 1:
[2, 3]

- [[1, 2], [2, 3]]
+ [[1, 3]]

----------------------------------------------------------------------
Ran 3 tests 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 `merge_ranges(ranges)` where each range is [start, end] with
start <= end. Return a new list of disjoint merged ranges sorted by start.

--- solution.py (buggy) ---
def merge_ranges(ranges):
 if not ranges:
 return []
 ordered = sorted(ranges, key=lambda r: r[0])
 out = [list(ordered[0])]
 for start, end in ordered[1:]:
 if start < out[-1][1]:
 out[-1][1] = max(out[-1][1], end)
 else:
 out.append([start, end])
 return out

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

class Test(unittest.TestCase):
 def test_overlap(self):
 self.assertEqual(merge_ranges([[1, 3], [2, 6], [8, 10]]), [[1, 6], [8, 10]])
 def test_touch(self):
 self.assertEqual(merge_ranges([[1, 2], [2, 3]]), [[1, 3]])
 def test_empty(self):
 self.assertEqual(merge_ranges([]), [])

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

test_empty (test_solution.Test.test_empty) ... ok
test_overlap (test_solution.Test.test_overlap) ... ok
test_touch (test_solution.Test.test_touch) ... FAIL

======================================================================
FAIL: test_touch (test_solution.Test.test_touch)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ajewpy74\test_solution.py", line 8, in test_touch
 self.assertEqual(merge_ranges([[1, 2], [2, 3]]), [[1, 3]])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [[1, 2], [2, 3]] != [[1, 3]]

First differing element 0:
[1, 2]
[1, 3]

First list contains 1 additional elements.
First extra element 1:
[2, 3]

- [[1, 2], [2, 3]]
+ [[1, 3]]

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1)


Answer:
from collections import defaultdict, deque

def topo_sort(nodes, edges):
 incoming = {n: 0 for n in nodes}
 graph = defaultdict(list)
 for src, dst in edges:
 graph[src].append(dst)
 incoming[dst] = incoming.get(dst, 0) + 1
 incoming.setdefault(src, incoming.get(src, 0))
 ready = deque([n for n in nodes if incoming.get(n, 0) == 0])
 order = []
 while ready:
 node = ready.popleft()
 order.append(node)
 for nxt in graph[node]:
 incoming[nxt] -= 1
 if incoming[nxt] == 0:
 ready.append(nxt)
 if len(order) != len(nodes):
 raise ValueError("cycle")
 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 defaultdict, deque

def topo_sort(nodes, edges):
    incoming = {n: 0 for n in nodes}
    graph = defaultdict(list)
    for src, dst in edges:
        graph[src].append(dst)
        incoming[dst] = incoming.get(dst, 0) + 1
        incoming.setdefault(src, incoming.get(src, 0))
    ready = deque([n for n in nodes if incoming.get(n, 0) == 0])
    order = []
    while ready:
        node = ready.popleft()
        order.append(node)
        for nxt in graph[node]:
            incoming[nxt] -= 1
            if incoming[nxt] == 0:
                ready.append(nxt)
    if len(order) != len(nodes):
        raise ValueError("cycle")
    return order

import unittest
from solution import topo_sort

class Test(unittest.TestCase):
    def test_chain(self):
        order = topo_sort(["a", "b", "c"], [("a", "b"), ("b", "c")])
        self.assertEqual(order, ["a", "b", "c"])
    def test_cycle(self):
        with self.assertRaises(ValueError):
            topo_sort(["a", "b"], [("a", "b"), ("b", "a")])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `topo_sort(nodes, edges)` for a directed acyclic graph.
`nodes` is a list of hashable ids. `edges` is a list of (src, dst) meaning
src must come before dst. Return any valid topological order. Raise ValueError
if a cycle exists.

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


Answer:
from collections import defaultdict, deque

def topo_sort(nodes, edges):
 incoming = {n: 0 for n in nodes}
 graph = defaultdict(list)
 for src, dst in edges:
 graph[src].append(dst)
 incoming[dst] = incoming.get(dst, 0) + 1
 incoming.setdefault(src, incoming.get(src, 0))
 ready = deque([n for n in nodes if incoming.get(n, 0) == 0])
 order = []
 while ready:
 node = ready.popleft()
 order.append(node)
 for nxt in graph[node]:
 incoming[nxt] -= 1
 if incoming[nxt] == 0:
 ready.append(nxt)
 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": 2, "failures": 1, "errors": 0, "skipped": 0, "passed": false}

test_chain (test_solution.Test.test_chain) ... FAIL
test_cycle (test_solution.Test.test_cycle) ... ok

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

First differing element 0:
'b'
'a'

- ['b', 'c', 'c']
+ ['a', 'b', 'c']

----------------------------------------------------------------------
Ran 2 tests 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 `topo_sort(nodes, edges)` for a directed acyclic graph.
`nodes` is a list of hashable ids. `edges` is a list of (src, dst) meaning
src must come before dst. Return any valid topological order. Raise ValueError
if a cycle exists.

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

def topo_sort(nodes, edges):
 incoming = {n: 0 for n in nodes}
 graph = defaultdict(list)
 for src, dst in edges:
 graph[src].append(dst)
 incoming[dst] = incoming.get(dst, 0) + 1
 incoming.setdefault(src, incoming.get(src, 0))
 ready = deque([n for n in nodes if incoming.get(n, 0) != 0])
 order = []
 while ready:
 node = ready.popleft()
 order.append(node)
 for nxt in graph[node]:
 incoming[nxt] -= 1
 if incoming[nxt] == 0:
 ready.append(nxt)
 if len(order) != len(nodes):
 raise ValueError("cycle")
 return order

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

class Test(unittest.TestCase):
 def test_chain(self):
 order = topo_sort(["a", "b", "c"], [("a", "b"), ("b", "c")])
 self.assertEqual(order, ["a", "b", "c"])
 def test_cycle(self):
 with self.assertRaises(ValueError):
 topo_sort(["a", "b"], [("a", "b"), ("b", "a")])

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

test_chain (test_solution.Test.test_chain) ... FAIL
test_cycle (test_solution.Test.test_cycle) ... ok

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

First differing element 0:
'b'
'a'

- ['b', 'c', 'c']
+ ['a', 'b', 'c']

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

FAILED (failures=1)


Answer:
import heapq

def shortest_cost(graph, start, goal):
 best = {start: 0}
 heap = [(0, start)]
 while heap:
 cost, node = heapq.heappop(heap)
 if cost != best.get(node, None):
 continue
 if node == goal:
 return cost
 for nxt, weight in graph.get(node, []):
 cand = cost + weight
 if cand < best.get(nxt, float("inf")):
 best[nxt] = cand
 heapq.heappush(heap, (cand, nxt))
 return None

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

The hidden tests in test_solution.py must pass.

import heapq

def shortest_cost(graph, start, goal):
    best = {start: 0}
    heap = [(0, start)]
    while heap:
        cost, node = heapq.heappop(heap)
        if cost != best.get(node, None):
            continue
        if node == goal:
            return cost
        for nxt, weight in graph.get(node, []):
            cand = cost + weight
            if cand < best.get(nxt, float("inf")):
                best[nxt] = cand
                heapq.heappush(heap, (cand, nxt))
    return None

import unittest
from solution import shortest_cost

class Test(unittest.TestCase):
    def test_path(self):
        g = {"s": [("a", 2), ("b", 5)], "a": [("g", 2)], "b": [("g", 1)], "g": []}
        self.assertEqual(shortest_cost(g, "s", "g"), 4)
    def test_missing(self):
        self.assertIsNone(shortest_cost({"s": []}, "s", "z"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `shortest_cost(graph, start, goal)` where graph maps node ->
list of (neighbor, weight) with non-negative weights. Return the minimum cost
or None if unreachable.


Answer:
import heapq

def shortest_cost(graph, start, goal):
 best = {start: 0}
 heap = [(0, start)]
 while heap:
 cost, node = heapq.heappop(heap)
 if cost != best.get(node, None):
 continue
 if node == goal:
 return cost
 for nxt, weight in graph.get(node, []):
 cand = cost + weight
 if cand < best.get(nxt, float("inf")):
 best[nxt] = cand
 heapq.heappush(heap, (cand, nxt))
 return None

Do not weaken or delete tests
Keep the public API

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

test_missing (test_solution.Test.test_missing) ... FAIL
test_path (test_solution.Test.test_path) ... FAIL

======================================================================
FAIL: test_missing (test_solution.Test.test_missing)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4tt_bkpa\test_solution.py", line 9, in test_missing
    self.assertIsNone(shortest_cost({"s": []}, "s", "z"))
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 is not None

======================================================================
FAIL: test_path (test_solution.Test.test_path)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4tt_bkpa\test_solution.py", line 7, in test_path
    self.assertEqual(shortest_cost(g, "s", "g"), 4)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != 4

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

FAILED (failures=2)

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 `shortest_cost(graph, start, goal)` where graph maps node ->
list of (neighbor, weight) with non-negative weights. Return the minimum cost
or None if unreachable.

--- solution.py (buggy) ---
import heapq

def shortest_cost(graph, start, goal):
 best = {start: 0}
 heap = [(0, start)]
 while heap:
 cost, node = heapq.heappop(heap)
 if cost != best.get(node, None):
 continue
 if node != goal:
 return cost
 for nxt, weight in graph.get(node, []):
 cand = cost + weight
 if cand < best.get(nxt, float("inf")):
 best[nxt] = cand
 heapq.heappush(heap, (cand, nxt))
 return None

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

class Test(unittest.TestCase):
 def test_path(self):
 g = {"s": [("a", 2), ("b", 5)], "a": [("g", 2)], "b": [("g", 1)], "g": []}
 self.assertEqual(shortest_cost(g, "s", "g"), 4)
 def test_missing(self):
 self.assertIsNone(shortest_cost({"s": []}, "s", "z"))

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

test_missing (test_solution.Test.test_missing) ... FAIL
test_path (test_solution.Test.test_path) ... FAIL

======================================================================
FAIL: test_missing (test_solution.Test.test_missing)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4tt_bkpa\test_solution.py", line 9, in test_missing
 self.assertIsNone(shortest_cost({"s": []}, "s", "z"))
 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 is not None

======================================================================
FAIL: test_path (test_solution.Test.test_path)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-4tt_bkpa\test_solution.py", line 7, in test_path
 self.assertEqual(shortest_cost(g, "s", "g"), 4)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != 4

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

FAILED (failures=2)


Answer:
import heapq

class RunningMedian:
 def __init__(self):
 self.low = []
 self.high = []

 def add(self, x):
 if not self.low or x <= -self.low[0]:
 heapq.heappush(self.low, -x)
 else:
 heapq.heappush(self.high, x)
 if len(self.low) > len(self.high) + 1:
 heapq.heappush(self.high, -heapq.heappop(self.low))
 elif len(self.high) > len(self.low):
 heapq.heappush(self.low, -heapq.heappop(self.high))

 def median(self):
 if not self.low:
 raise ValueError("empty")
 if len(self.low) > len(self.high):
 return float(-self.low[0])
 return (-self.low[0] + self.high[0]) / 2.0

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

The hidden tests in test_solution.py must pass.

import heapq

class RunningMedian:
    def __init__(self):
        self.low = []
        self.high = []

    def add(self, x):
        if not self.low or x <= -self.low[0]:
            heapq.heappush(self.low, -x)
        else:
            heapq.heappush(self.high, x)
        if len(self.low) > len(self.high) + 1:
            heapq.heappush(self.high, -heapq.heappop(self.low))
        elif len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):
        if not self.low:
            raise ValueError("empty")
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2.0

import unittest
from solution import RunningMedian

class Test(unittest.TestCase):
    def test_stream(self):
        r = RunningMedian()
        for x in [5, 2, 8, 1]:
            r.add(x)
        self.assertEqual(r.median(), 3.5)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement class `RunningMedian` with `add(x)` and `median()` (mean of the
two center values when the count is even). Values are numbers.


Answer:
def parse_kv(text):
 result = {}
 for raw in text.splitlines():
 line = raw.strip()
 if not line or line.startswith("#"):
 continue
 if "=" not in line:
 raise ValueError(line)
 key, value = line.split("=", 1)
 result[key.strip()] = value.strip()
 return result

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

The hidden tests in test_solution.py must pass.

def parse_kv(text):
    result = {}
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            raise ValueError(line)
        key, value = line.split("=", 1)
        result[key.strip()] = value.strip()
    return result

import unittest
from solution import parse_kv

class Test(unittest.TestCase):
    def test_parse(self):
        text = "# c\nport = 80\nhost = a=b\nport = 8080\n"
        self.assertEqual(parse_kv(text), {"port": "8080", "host": "a=b"})
    def test_bad(self):
        with self.assertRaises(ValueError):
            parse_kv("oops")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_kv(text)` for a tiny config language:
- ignore blank lines and lines starting with `#`
- remaining lines are `key = value` (value trimmed, may contain =)
- duplicate keys: last wins
Return a dict. Raise ValueError on lines without `=`.


Answer:
def cmp_semver(a, b):
 def parts(s):
 bits = s.split(".")
 if len(bits) != 3 or not all(p.isdigit() for p in bits):
 raise ValueError(s)
 return tuple(int(p) for p in bits)
 left, right = parts(a), parts(b)
 return (left > right) - (left < right)

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

The hidden tests in test_solution.py must pass.

def cmp_semver(a, b):
    def parts(s):
        bits = s.split(".")
        if len(bits) != 3 or not all(p.isdigit() for p in bits):
            raise ValueError(s)
        return tuple(int(p) for p in bits)
    left, right = parts(a), parts(b)
    return (left > right) - (left < right)

import unittest
from solution import cmp_semver

class Test(unittest.TestCase):
    def test_cmp(self):
        self.assertEqual(cmp_semver("1.2.0", "1.10.0"), -1)
        self.assertEqual(cmp_semver("2.0.0", "2.0.0"), 0)
        self.assertEqual(cmp_semver("1.0.1", "1.0.0"), 1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `cmp_semver(a, b)` comparing MAJOR.MINOR.PATCH strings (digits
only, no pre-release). Return -1, 0, or 1.


Answer:
def cmp_semver(a, b):
 def parts(s):
 bits = s.split(".")
 if len(bits) != 3 or not all(p.isdigit() for p in bits):
 raise ValueError(s)
 return tuple(int(p) for p in bits)
 left, right = parts(a), parts(b)
 return (left > right) - (left < right)

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_cmp (test_solution.Test.test_cmp) ... FAIL

======================================================================
FAIL: test_cmp (test_solution.Test.test_cmp)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ez7l14g8\test_solution.py", line 6, in test_cmp
    self.assertEqual(cmp_semver("1.2.0", "1.10.0"), -1)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != -1

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

FAILED (failures=1)

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 `cmp_semver(a, b)` comparing MAJOR.MINOR.PATCH strings (digits
only, no pre-release). Return -1, 0, or 1.

--- solution.py (buggy) ---
def cmp_semver(a, b):
 return (a > b) - (a < b)

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

class Test(unittest.TestCase):
 def test_cmp(self):
 self.assertEqual(cmp_semver("1.2.0", "1.10.0"), -1)
 self.assertEqual(cmp_semver("2.0.0", "2.0.0"), 0)
 self.assertEqual(cmp_semver("1.0.1", "1.0.0"), 1)

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

test_cmp (test_solution.Test.test_cmp) ... FAIL

======================================================================
FAIL: test_cmp (test_solution.Test.test_cmp)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ez7l14g8\test_solution.py", line 6, in test_cmp
 self.assertEqual(cmp_semver("1.2.0", "1.10.0"), -1)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != -1

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

FAILED (failures=1)


Answer:
def pins_ok(declared, locked):
 for name, minimum in declared.items():
 if name not in locked:
 return False
 if locked[name] < minimum:
 return False
 return True

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

The hidden tests in test_solution.py must pass.

def pins_ok(declared, locked):
    for name, minimum in declared.items():
        if name not in locked:
            return False
        if locked[name] < minimum:
            return False
    return True

import unittest
from solution import pins_ok

class Test(unittest.TestCase):
    def test_ok(self):
        self.assertTrue(pins_ok({"a": (1, 2, 0)}, {"a": (1, 2, 3), "b": (0, 1, 0)}))
    def test_missing(self):
        self.assertFalse(pins_ok({"a": (1, 0, 0)}, {}))
    def test_old(self):
        self.assertFalse(pins_ok({"a": (2, 0, 0)}, {"a": (1, 9, 9)}))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `pins_ok(declared, locked)` where declared maps package ->
minimum inclusive version tuple (major, minor, patch) and locked maps package
-> installed version tuple. Every declared package must be present and
installed >= minimum. Extra locked packages are allowed.

test_missing (test_solution.Test.test_missing) ... ok
test_ok (test_solution.Test.test_ok) ... ok
test_old (test_solution.Test.test_old) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK


Answer:
def pins_ok(declared, locked):
 for name, minimum in declared.items():
 if name not in locked:
 return False
 if locked[name] < minimum:
 return False
 return True

Do not weaken or delete tests
Keep the public API

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

test_missing (test_solution.Test.test_missing) ... ok
test_ok (test_solution.Test.test_ok) ... FAIL
test_old (test_solution.Test.test_old) ... ok

======================================================================
FAIL: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-70mezklv\test_solution.py", line 6, in test_ok
    self.assertTrue(pins_ok({"a": (1, 2, 0)}, {"a": (1, 2, 3), "b": (0, 1, 0)}))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 3 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.

Implement `pins_ok(declared, locked)` where declared maps package ->
minimum inclusive version tuple (major, minor, patch) and locked maps package
-> installed version tuple. Every declared package must be present and
installed >= minimum. Extra locked packages are allowed.

--- solution.py (buggy) ---
def pins_ok(declared, locked):
 for name, minimum in declared.items():
 if name not in locked:
 return False
 if locked[name] < minimum:
 return False
 return False

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

class Test(unittest.TestCase):
 def test_ok(self):
 self.assertTrue(pins_ok({"a": (1, 2, 0)}, {"a": (1, 2, 3), "b": (0, 1, 0)}))
 def test_missing(self):
 self.assertFalse(pins_ok({"a": (1, 0, 0)}, {}))
 def test_old(self):
 self.assertFalse(pins_ok({"a": (2, 0, 0)}, {"a": (1, 9, 9)}))

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

test_missing (test_solution.Test.test_missing) ... ok
test_ok (test_solution.Test.test_ok) ... FAIL
test_old (test_solution.Test.test_old) ... ok

======================================================================
FAIL: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-70mezklv\test_solution.py", line 6, in test_ok
 self.assertTrue(pins_ok({"a": (1, 2, 0)}, {"a": (1, 2, 3), "b": (0, 1, 0)}))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (failures=1)


Answer:
import re

def quote_ident(name):
 if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
 raise ValueError("invalid identifier")
 return '"' + name.replace('"', '""') + '"'

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

The hidden tests in test_solution.py must pass.

import re

def quote_ident(name):
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
        raise ValueError("invalid identifier")
    return '"' + name.replace('"', '""') + '"'

import unittest
from solution import quote_ident

class Test(unittest.TestCase):
    def test_ok(self):
        self.assertEqual(quote_ident("user_id"), '"user_id"')
    def test_reject(self):
        with self.assertRaises(ValueError):
            quote_ident("user-id")
        with self.assertRaises(ValueError):
            quote_ident("1x")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `quote_ident(name)` for a conservative SQL identifier:
accept only `[A-Za-z_][A-Za-z0-9_]*` and wrap in double quotes with internal
quotes doubled. Raise ValueError otherwise. This is defensive quoting, not a
parser for arbitrary SQL.


Answer:
import re

def quote_ident(name):
 if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
 raise ValueError("invalid identifier")
 return '"' + name.replace('"', '""') + '"'

Do not weaken or delete tests
Keep the public API

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

test_ok (test_solution.Test.test_ok) ... ERROR
test_reject (test_solution.Test.test_reject) ... ok

======================================================================
ERROR: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-o5h0j4in\test_solution.py", line 6, in test_ok
    self.assertEqual(quote_ident("user_id"), '"user_id"')
                     ~~~~~~~~~~~^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-o5h0j4in\solution.py", line 6, in quote_ident
    return '"' - name.replace('"', '""') + '"'
           ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

----------------------------------------------------------------------
Ran 2 tests 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 `quote_ident(name)` for a conservative SQL identifier:
accept only `[A-Za-z_][A-Za-z0-9_]*` and wrap in double quotes with internal
quotes doubled. Raise ValueError otherwise. This is defensive quoting, not a
parser for arbitrary SQL.

--- solution.py (buggy) ---
import re

def quote_ident(name):
 if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
 raise ValueError("invalid identifier")
 return '"' - name.replace('"', '""') + '"'

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

class Test(unittest.TestCase):
 def test_ok(self):
 self.assertEqual(quote_ident("user_id"), '"user_id"')
 def test_reject(self):
 with self.assertRaises(ValueError):
 quote_ident("user-id")
 with self.assertRaises(ValueError):
 quote_ident("1x")

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

test_ok (test_solution.Test.test_ok) ... ERROR
test_reject (test_solution.Test.test_reject) ... ok

======================================================================
ERROR: test_ok (test_solution.Test.test_ok)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-o5h0j4in\test_solution.py", line 6, in test_ok
 self.assertEqual(quote_ident("user_id"), '"user_id"')
 ~~~~~~~~~~~^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-o5h0j4in\solution.py", line 6, in quote_ident
 return '"' - name.replace('"', '""') + '"'
 ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

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

FAILED (errors=1)


Answer:
import re

def safe_select_by_id(conn, table, row_id):
 if not re.fullmatch(r"[a-z_]+", table):
 raise ValueError("table")
 sql = f'SELECT * FROM "{table}" WHERE id = ?'
 return list(conn.execute(sql, (row_id,)))

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

The hidden tests in test_solution.py must pass.

import re

def safe_select_by_id(conn, table, row_id):
    if not re.fullmatch(r"[a-z_]+", table):
        raise ValueError("table")
    sql = f'SELECT * FROM "{table}" WHERE id = ?'
    return list(conn.execute(sql, (row_id,)))

import sqlite3
import unittest
from solution import safe_select_by_id

class Test(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(":memory:")
        self.conn.execute("CREATE TABLE items (id INTEGER, name TEXT)")
        self.conn.execute("INSERT INTO items VALUES (1, 'a'), (2, 'b')")

    def test_param(self):
        rows = safe_select_by_id(self.conn, "items", 2)
        self.assertEqual(rows, [(2, "b")])

    def test_injection_value(self):
        rows = safe_select_by_id(self.conn, "items", "2 OR 1=1")
        self.assertEqual(rows, [])

    def test_bad_table(self):
        with self.assertRaises(ValueError):
            safe_select_by_id(self.conn, "items;drop", 1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `safe_select_by_id(conn, table, row_id)` using sqlite3.
`table` must match `[a-z_]+`. Execute a parameterized query
`SELECT * FROM {table} WHERE id = ?` and return the list of rows.
Never interpolate `row_id` into the SQL string.

test_bad_table (test_solution.Test.test_bad_table) ... ok
test_injection_value (test_solution.Test.test_injection_value) ... ok
test_param (test_solution.Test.test_param) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK


Answer:
from pathlib import Path

def resolve_under(root, relative):
 base = Path(root).resolve()
 target = (base / relative).resolve()
 try:
 target.relative_to(base)
 except ValueError as exc:
 raise ValueError("escape") from exc
 return str(target)

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

The hidden tests in test_solution.py must pass.

from pathlib import Path

def resolve_under(root, relative):
    base = Path(root).resolve()
    target = (base / relative).resolve()
    try:
        target.relative_to(base)
    except ValueError as exc:
        raise ValueError("escape") from exc
    return str(target)

import tempfile
import unittest
from pathlib import Path
from solution import resolve_under

class Test(unittest.TestCase):
    def test_inside(self):
        with tempfile.TemporaryDirectory() as td:
            p = resolve_under(td, "a/b.txt")
            self.assertTrue(p.startswith(str(Path(td).resolve())))
    def test_escape(self):
        with tempfile.TemporaryDirectory() as td:
            with self.assertRaises(ValueError):
                resolve_under(td, "../secret")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `resolve_under(root, relative)` that joins `relative` to `root`
and returns the resolved path only if it stays inside `root`. Reject `..`
escapes. Use pathlib. Raise ValueError on escape.


Answer:
import ipaddress

def ipv4_in_cidr(ip, cidr):
 return ipaddress.IPv4Address(ip) in ipaddress.IPv4Network(cidr, strict=False)

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

The hidden tests in test_solution.py must pass.

import ipaddress

def ipv4_in_cidr(ip, cidr):
    return ipaddress.IPv4Address(ip) in ipaddress.IPv4Network(cidr, strict=False)

import unittest
from solution import ipv4_in_cidr

class Test(unittest.TestCase):
    def test_in(self):
        self.assertTrue(ipv4_in_cidr("10.1.2.3", "10.0.0.0/8"))
    def test_out(self):
        self.assertFalse(ipv4_in_cidr("11.0.0.1", "10.0.0.0/8"))
    def test_exact(self):
        self.assertTrue(ipv4_in_cidr("192.0.2.1", "192.0.2.1/32"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `ipv4_in_cidr(ip, cidr)` where ip is dotted IPv4 and cidr is
like `10.0.0.0/8`. Return True iff the address is in the prefix. No extra
libraries beyond stdlib.

test_exact (test_solution.Test.test_exact) ... ok
test_in (test_solution.Test.test_in) ... ok
test_out (test_solution.Test.test_out) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK


Answer:
def fcfs_completion(jobs):
 time = 0
 done = []
 for arrival, burst in jobs:
 time = max(time, arrival) + burst
 done.append(time)
 return done

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

The hidden tests in test_solution.py must pass.

def fcfs_completion(jobs):
    time = 0
    done = []
    for arrival, burst in jobs:
        time = max(time, arrival) + burst
        done.append(time)
    return done

import unittest
from solution import fcfs_completion

class Test(unittest.TestCase):
    def test_idle(self):
        self.assertEqual(fcfs_completion([(0, 3), (5, 2)]), [3, 7])
    def test_queue(self):
        self.assertEqual(fcfs_completion([(0, 2), (1, 2)]), [2, 4])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `fcfs_completion(jobs)` where each job is (arrival, burst) and
jobs are already ordered by arrival time (ties keep given order). Return a list
of completion times in the same order. The CPU is idle until the next arrival
if needed.


Answer:
def fcfs_completion(jobs):
 time = 0
 done = []
 for arrival, burst in jobs:
 time = max(time, arrival) + burst
 done.append(time)
 return done

Do not weaken or delete tests
Keep the public API

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

test_idle (test_solution.Test.test_idle) ... FAIL
test_queue (test_solution.Test.test_queue) ... FAIL

======================================================================
FAIL: test_idle (test_solution.Test.test_idle)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0uak84hz\test_solution.py", line 6, in test_idle
    self.assertEqual(fcfs_completion([(0, 3), (5, 2)]), [3, 7])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [-3, 3] != [3, 7]

First differing element 0:
-3
3

- [-3, 3]
?  -   ^

+ [3, 7]
?     ^

======================================================================
FAIL: test_queue (test_solution.Test.test_queue)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0uak84hz\test_solution.py", line 8, in test_queue
    self.assertEqual(fcfs_completion([(0, 2), (1, 2)]), [2, 4])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [-2, -1] != [2, 4]

First differing element 0:
-2
2

- [-2, -1]
+ [2, 4]

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

FAILED (failures=2)

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 `fcfs_completion(jobs)` where each job is (arrival, burst) and
jobs are already ordered by arrival time (ties keep given order). Return a list
of completion times in the same order. The CPU is idle until the next arrival
if needed.

--- solution.py (buggy) ---
def fcfs_completion(jobs):
 time = 0
 done = []
 for arrival, burst in jobs:
 time = max(time, arrival) - burst
 done.append(time)
 return done

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

class Test(unittest.TestCase):
 def test_idle(self):
 self.assertEqual(fcfs_completion([(0, 3), (5, 2)]), [3, 7])
 def test_queue(self):
 self.assertEqual(fcfs_completion([(0, 2), (1, 2)]), [2, 4])

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

test_idle (test_solution.Test.test_idle) ... FAIL
test_queue (test_solution.Test.test_queue) ... FAIL

======================================================================
FAIL: test_idle (test_solution.Test.test_idle)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0uak84hz\test_solution.py", line 6, in test_idle
 self.assertEqual(fcfs_completion([(0, 3), (5, 2)]), [3, 7])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [-3, 3] != [3, 7]

First differing element 0:
-3
3

- [-3, 3]
? - ^

+ [3, 7]
? ^

======================================================================
FAIL: test_queue (test_solution.Test.test_queue)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-0uak84hz\test_solution.py", line 8, in test_queue
 self.assertEqual(fcfs_completion([(0, 2), (1, 2)]), [2, 4])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [-2, -1] != [2, 4]

First differing element 0:
-2
2

- [-2, -1]
+ [2, 4]

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

FAILED (failures=2)


Answer:
from collections import deque

def rr_finish(bursts, quantum):
 remaining = list(bursts)
 finish = [None] * len(bursts)
 q = deque(range(len(bursts)))
 t = 0
 while q:
 i = q.popleft()
 run = min(quantum, remaining[i])
 remaining[i] -= run
 t += run
 if remaining[i] == 0:
 finish[i] = t
 else:
 q.append(i)
 return finish

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 rr_finish(bursts, quantum):
    remaining = list(bursts)
    finish = [None] * len(bursts)
    q = deque(range(len(bursts)))
    t = 0
    while q:
        i = q.popleft()
        run = min(quantum, remaining[i])
        remaining[i] -= run
        t += run
        if remaining[i] == 0:
            finish[i] = t
        else:
            q.append(i)
    return finish

import unittest
from solution import rr_finish

class Test(unittest.TestCase):
    def test_rr(self):
        self.assertEqual(rr_finish([5, 3, 1], 2), [9, 8, 5])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `rr_finish(bursts, quantum)` for processes all arriving at 0,
indexed 0..n-1, using a FIFO ready queue. Return completion times list.
Ignore context-switch cost.


Answer:
from collections import deque

def rr_finish(bursts, quantum):
 remaining = list(bursts)
 finish = [None] * len(bursts)
 q = deque(range(len(bursts)))
 t = 0
 while q:
 i = q.popleft()
 run = min(quantum, remaining[i])
 remaining[i] -= run
 t += run
 if remaining[i] == 0:
 finish[i] = t
 else:
 q.append(i)
 return finish

Do not weaken or delete tests
Keep the public API

Output: test_rr (test_solution.Test.test_rr) ...

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 `rr_finish(bursts, quantum)` for processes all arriving at 0,
indexed 0..n-1, using a FIFO ready queue. Return completion times list.
Ignore context-switch cost.

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

def rr_finish(bursts, quantum):
 remaining = list(bursts)
 finish = [None] * len(bursts)
 q = deque(range(len(bursts)))
 t = 0
 while q:
 i = q.popleft()
 run = min(quantum, remaining[i])
 remaining[i] -= run
 t += run
 if remaining[i] != 0:
 finish[i] = t
 else:
 q.append(i)
 return finish

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

class Test(unittest.TestCase):
 def test_rr(self):
 self.assertEqual(rr_finish([5, 3, 1], 2), [9, 8, 5])

--- failure ---

test_rr (test_solution.Test.test_rr) ...


Answer:
def lru_faults(pages, frames):
 slot = []
 used = []
 faults = 0
 for page in pages:
 if page in slot:
 used.remove(page)
 used.append(page)
 continue
 faults += 1
 if len(slot) < frames:
 slot.append(page)
 else:
 victim = used.pop(0)
 idx = slot.index(victim)
 slot[idx] = page
 used.append(page)
 return faults

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

The hidden tests in test_solution.py must pass.

def lru_faults(pages, frames):
    slot = []
    used = []
    faults = 0
    for page in pages:
        if page in slot:
            used.remove(page)
            used.append(page)
            continue
        faults += 1
        if len(slot) < frames:
            slot.append(page)
        else:
            victim = used.pop(0)
            idx = slot.index(victim)
            slot[idx] = page
        used.append(page)
    return faults

import unittest
from solution import lru_faults

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

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `lru_faults(pages, frames)` counting page faults with LRU
replacement among `frames` slots. Empty frames fill first.


Answer:
def is_safe(available, allocation, need):
 work = list(available)
 finish = [False] * len(allocation)
 while True:
 progressed = False
 for i, done in enumerate(finish):
 if done:
 continue
 if all(need[i][j] <= work[j] for j in range(len(work))):
 for j in range(len(work)):
 work[j] += allocation[i][j]
 finish[i] = True
 progressed = True
 if not progressed:
 break
 return all(finish)

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

The hidden tests in test_solution.py must pass.

def is_safe(available, allocation, need):
    work = list(available)
    finish = [False] * len(allocation)
    while True:
        progressed = False
        for i, done in enumerate(finish):
            if done:
                continue
            if all(need[i][j] <= work[j] for j in range(len(work))):
                for j in range(len(work)):
                    work[j] += allocation[i][j]
                finish[i] = True
                progressed = True
        if not progressed:
            break
    return all(finish)

import unittest
from solution import is_safe

class Test(unittest.TestCase):
    def test_safe(self):
        self.assertTrue(is_safe([3], [[0], [1], [1]], [[1], [0], [2]]))
    def test_unsafe(self):
        self.assertFalse(is_safe([0], [[1], [1]], [[1], [1]]))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `is_safe(available, allocation, need)` for the Banker's algorithm
safety check. `available` is a list of resource counts. `allocation` and `need`
are lists of per-process lists. Return True iff a safe sequence exists.


Answer:
class TokenBucket:
 def __init__(self, rate, burst):
 self.rate = rate
 self.burst = burst
 self.tokens = float(burst)
 self.t = 0.0

 def allow(self, time, cost=1):
 if time < self.t:
 raise ValueError("time")
 self.tokens = min(self.burst, self.tokens + (time - self.t) * self.rate)
 self.t = time
 if self.tokens >= cost:
 self.tokens -= cost
 return True
 return False

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

The hidden tests in test_solution.py must pass.

class TokenBucket:
    def __init__(self, rate, burst):
        self.rate = rate
        self.burst = burst
        self.tokens = float(burst)
        self.t = 0.0

    def allow(self, time, cost=1):
        if time < self.t:
            raise ValueError("time")
        self.tokens = min(self.burst, self.tokens + (time - self.t) * self.rate)
        self.t = time
        if self.tokens >= cost:
            self.tokens -= cost
            return True
        return False

import unittest
from solution import TokenBucket

class Test(unittest.TestCase):
    def test_burst_then_refill(self):
        b = TokenBucket(1.0, 2)
        self.assertTrue(b.allow(0))
        self.assertTrue(b.allow(0))
        self.assertFalse(b.allow(0))
        self.assertTrue(b.allow(1.0))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement class `TokenBucket(rate, burst)` with `allow(time, cost=1)`.
`rate` is tokens per time unit, `burst` is max tokens. Start full at t=0.
`time` is non-decreasing. Return True if the request is admitted.


Answer:
class TokenBucket:
 def __init__(self, rate, burst):
 self.rate = rate
 self.burst = burst
 self.tokens = float(burst)
 self.t = 0.0

 def allow(self, time, cost=1):
 if time < self.t:
 raise ValueError("time")
 self.tokens = min(self.burst, self.tokens + (time - self.t) * self.rate)
 self.t = time
 if self.tokens >= cost:
 self.tokens -= cost
 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_burst_then_refill (test_solution.Test.test_burst_then_refill) ... FAIL

======================================================================
FAIL: test_burst_then_refill (test_solution.Test.test_burst_then_refill)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-xgf9vhaq\test_solution.py", line 7, in test_burst_then_refill
    self.assertTrue(b.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 class `TokenBucket(rate, burst)` with `allow(time, cost=1)`.
`rate` is tokens per time unit, `burst` is max tokens. Start full at t=0.
`time` is non-decreasing. Return True if the request is admitted.

--- solution.py (buggy) ---
class TokenBucket:
 def __init__(self, rate, burst):
 self.rate = rate
 self.burst = burst
 self.tokens = float(burst)
 self.t = 0.0

 def allow(self, time, cost=1):
 if time < self.t:
 raise ValueError("time")
 self.tokens = min(self.burst, self.tokens + (time - self.t) * self.rate)
 self.t = time
 if self.tokens >= cost:
 self.tokens -= cost
 return False
 return False

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

class Test(unittest.TestCase):
 def test_burst_then_refill(self):
 b = TokenBucket(1.0, 2)
 self.assertTrue(b.allow(0))
 self.assertTrue(b.allow(0))
 self.assertFalse(b.allow(0))
 self.assertTrue(b.allow(1.0))

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

test_burst_then_refill (test_solution.Test.test_burst_then_refill) ... FAIL

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

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

FAILED (failures=1)


Answer:
def missing_required(schema, payload):
 types = {"string": str, "number": (int, float), "boolean": bool}
 bad = []
 for name in schema.get("required", []):
 if name not in payload:
 bad.append(name)
 continue
 declared = schema["properties"][name]["type"]
 if declared == "number" and isinstance(payload[name], bool):
 bad.append(name)
 continue
 if not isinstance(payload[name], types[declared]):
 bad.append(name)
 return sorted(bad)

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

The hidden tests in test_solution.py must pass.

def missing_required(schema, payload):
    types = {"string": str, "number": (int, float), "boolean": bool}
    bad = []
    for name in schema.get("required", []):
        if name not in payload:
            bad.append(name)
            continue
        declared = schema["properties"][name]["type"]
        if declared == "number" and isinstance(payload[name], bool):
            bad.append(name)
            continue
        if not isinstance(payload[name], types[declared]):
            bad.append(name)
    return sorted(bad)

import unittest
from solution import missing_required

class Test(unittest.TestCase):
    def test_types(self):
        schema = {
            "required": ["id", "ok"],
            "properties": {"id": {"type": "number"}, "ok": {"type": "boolean"}},
        }
        self.assertEqual(missing_required(schema, {"id": True, "ok": True}), ["id"])
        self.assertEqual(missing_required(schema, {"id": 1, "ok": True}), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `missing_required(schema, payload)` where schema is
`{"required": [...], "properties": {name: {"type": "string"|"number"|"boolean"}}}`.
Return sorted names that are missing or have the wrong JSON type.
Extra payload keys are ignored.


Answer:
def missing_required(schema, payload):
 types = {"string": str, "number": (int, float), "boolean": bool}
 bad = []
 for name in schema.get("required", []):
 if name not in payload:
 bad.append(name)
 continue
 declared = schema["properties"][name]["type"]
 if declared == "number" and isinstance(payload[name], bool):
 bad.append(name)
 continue
 if not isinstance(payload[name], types[declared]):
 bad.append(name)
 return sorted(bad)

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_types (test_solution.Test.test_types) ... FAIL

======================================================================
FAIL: test_types (test_solution.Test.test_types)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-qvs7oov5\test_solution.py", line 10, in test_types
    self.assertEqual(missing_required(schema, {"id": True, "ok": True}), ["id"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['ok'] != ['id']

First differing element 0:
'ok'
'id'

- ['ok']
+ ['id']

----------------------------------------------------------------------
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 `missing_required(schema, payload)` where schema is
`{"required": [...], "properties": {name: {"type": "string"|"number"|"boolean"}}}`.
Return sorted names that are missing or have the wrong JSON type.
Extra payload keys are ignored.

--- solution.py (buggy) ---
def missing_required(schema, payload):
 types = {"string": str, "number": (int, float), "boolean": bool}
 bad = []
 for name in schema.get("required", []):
 if name not in payload:
 bad.append(name)
 continue
 declared = schema["properties"][name]["type"]
 if declared != "number" and isinstance(payload[name], bool):
 bad.append(name)
 continue
 if not isinstance(payload[name], types[declared]):
 bad.append(name)
 return sorted(bad)

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

class Test(unittest.TestCase):
 def test_types(self):
 schema = {
 "required": ["id", "ok"],
 "properties": {"id": {"type": "number"}, "ok": {"type": "boolean"}},
 }
 self.assertEqual(missing_required(schema, {"id": True, "ok": True}), ["id"])
 self.assertEqual(missing_required(schema, {"id": 1, "ok": True}), [])

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

test_types (test_solution.Test.test_types) ... FAIL

======================================================================
FAIL: test_types (test_solution.Test.test_types)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-qvs7oov5\test_solution.py", line 10, in test_types
 self.assertEqual(missing_required(schema, {"id": True, "ok": True}), ["id"])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: ['ok'] != ['id']

First differing element 0:
'ok'
'id'

- ['ok']
+ ['id']

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

FAILED (failures=1)


Answer:
def allowed_import(from_layer, to_layer, rules):
 if from_layer == to_layer:
 return True
 allowed = set(rules)
 return (from_layer, to_layer) in allowed

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

The hidden tests in test_solution.py must pass.

def allowed_import(from_layer, to_layer, rules):
    if from_layer == to_layer:
        return True
    allowed = set(rules)
    return (from_layer, to_layer) in allowed

import unittest
from solution import allowed_import

class Test(unittest.TestCase):
    def test_hex(self):
        rules = [("app", "domain"), ("infra", "domain")]
        self.assertTrue(allowed_import("app", "domain", rules))
        self.assertFalse(allowed_import("domain", "infra", rules))
        self.assertTrue(allowed_import("domain", "domain", rules))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `allowed_import(from_layer, to_layer, rules)` where layers are
strings and rules is a list of (src, dst) allowed edges. A module may always
import from its own layer. Return True iff the import is permitted.


Answer:
def allowed_import(from_layer, to_layer, rules):
 if from_layer == to_layer:
 return True
 allowed = set(rules)
 return (from_layer, to_layer) in allowed

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_hex (test_solution.Test.test_hex) ... FAIL

======================================================================
FAIL: test_hex (test_solution.Test.test_hex)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-1ukbywm_\test_solution.py", line 9, in test_hex
    self.assertTrue(allowed_import("domain", "domain", rules))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
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 `allowed_import(from_layer, to_layer, rules)` where layers are
strings and rules is a list of (src, dst) allowed edges. A module may always
import from its own layer. Return True iff the import is permitted.

--- solution.py (buggy) ---
def allowed_import(from_layer, to_layer, rules):
 if from_layer == to_layer:
 return False
 allowed = set(rules)
 return (from_layer, to_layer) in allowed

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

class Test(unittest.TestCase):
 def test_hex(self):
 rules = [("app", "domain"), ("infra", "domain")]
 self.assertTrue(allowed_import("app", "domain", rules))
 self.assertFalse(allowed_import("domain", "infra", rules))
 self.assertTrue(allowed_import("domain", "domain", rules))

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

test_hex (test_solution.Test.test_hex) ... FAIL

======================================================================
FAIL: test_hex (test_solution.Test.test_hex)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-1ukbywm_\test_solution.py", line 9, in test_hex
 self.assertTrue(allowed_import("domain", "domain", rules))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

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

FAILED (failures=1)


Answer:
def eval_rpn(tokens):
 stack = []
 ops = {
 "+": lambda a, b: a + b,
 "-": lambda a, b: a - b,
 "*": lambda a, b: a * b,
 "/": lambda a, b: a // b,
 }
 for tok in tokens:
 if tok in ops:
 b = stack.pop()
 a = stack.pop()
 stack.append(ops[tok](a, b))
 else:
 stack.append(int(tok))
 if len(stack) != 1:
 raise ValueError("rpn")
 return stack[0]

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

The hidden tests in test_solution.py must pass.

def eval_rpn(tokens):
    stack = []
    ops = {
        "+": lambda a, b: a + b,
        "-": lambda a, b: a - b,
        "*": lambda a, b: a * b,
        "/": lambda a, b: a // b,
    }
    for tok in tokens:
        if tok in ops:
            b = stack.pop()
            a = stack.pop()
            stack.append(ops[tok](a, b))
        else:
            stack.append(int(tok))
    if len(stack) != 1:
        raise ValueError("rpn")
    return stack[0]

import unittest
from solution import eval_rpn

class Test(unittest.TestCase):
    def test_expr(self):
        self.assertEqual(eval_rpn(["2", "3", "4", "*", "+"]), 14)
    def test_div(self):
        self.assertEqual(eval_rpn(["7", "2", "/"]), 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `eval_rpn(tokens)` for integers and + - * / (integer division
toward zero is NOT required: use Python `//` toward -inf). Tokens are strings.


Answer:
def eval_rpn(tokens):
 stack = []
 ops = {
 "+": lambda a, b: a + b,
 "-": lambda a, b: a - b,
 "*": lambda a, b: a * b,
 "/": lambda a, b: a // b,
 }
 for tok in tokens:
 if tok in ops:
 b = stack.pop()
 a = stack.pop()
 stack.append(ops[tok](a, b))
 else:
 stack.append(int(tok))
 if len(stack) != 1:
 raise ValueError("rpn")
 return stack[0]

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_div (test_solution.Test.test_div) ... ok
test_expr (test_solution.Test.test_expr) ... FAIL

======================================================================
FAIL: test_expr (test_solution.Test.test_expr)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-x9yaho2a\test_solution.py", line 6, in test_expr
    self.assertEqual(eval_rpn(["2", "3", "4", "*", "+"]), 14)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -10 != 14

----------------------------------------------------------------------
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.

Implement `eval_rpn(tokens)` for integers and + - * / (integer division
toward zero is NOT required: use Python `//` toward -inf). Tokens are strings.

--- solution.py (buggy) ---
def eval_rpn(tokens):
 stack = []
 ops = {
 "+": lambda a, b: a - b,
 "-": lambda a, b: a - b,
 "*": lambda a, b: a * b,
 "/": lambda a, b: a // b,
 }
 for tok in tokens:
 if tok in ops:
 b = stack.pop()
 a = stack.pop()
 stack.append(ops[tok](a, b))
 else:
 stack.append(int(tok))
 if len(stack) != 1:
 raise ValueError("rpn")
 return stack[0]

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

class Test(unittest.TestCase):
 def test_expr(self):
 self.assertEqual(eval_rpn(["2", "3", "4", "*", "+"]), 14)
 def test_div(self):
 self.assertEqual(eval_rpn(["7", "2", "/"]), 3)

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

test_div (test_solution.Test.test_div) ... ok
test_expr (test_solution.Test.test_expr) ... FAIL

======================================================================
FAIL: test_expr (test_solution.Test.test_expr)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-x9yaho2a\test_solution.py", line 6, in test_expr
 self.assertEqual(eval_rpn(["2", "3", "4", "*", "+"]), 14)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -10 != 14

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

FAILED (failures=1)


Answer:
def occurs(var, typ):
 if typ == var:
 return True
 if isinstance(typ, list):
 return any(occurs(var, part) for part in typ[1:])
 return False

def apply_sub(sub, typ):
 if isinstance(typ, str):
 return sub.get(typ, typ)
 return [typ[0], *(apply_sub(sub, p) for p in typ[1:])]

def unify(a, b, sub=None):
 sub = dict(sub or {})
 a, b = apply_sub(sub, a), apply_sub(sub, b)
 if a == b:
 return sub
 if isinstance(a, str) and a.startswith("?"):
 if occurs(a, b):
 return None
 sub[a] = b
 return sub
 if isinstance(b, str) and b.startswith("?"):
 return unify(b, a, sub)
 if isinstance(a, list) and isinstance(b, list) and a[0] == b[0] and len(a) == len(b):
 for x, y in zip(a[1:], b[1:]):
 sub = unify(x, y, sub)
 if sub is None:
 return None
 return sub
 return None

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

The hidden tests in test_solution.py must pass.

def occurs(var, typ):
    if typ == var:
        return True
    if isinstance(typ, list):
        return any(occurs(var, part) for part in typ[1:])
    return False

def apply_sub(sub, typ):
    if isinstance(typ, str):
        return sub.get(typ, typ)
    return [typ[0], *(apply_sub(sub, p) for p in typ[1:])]

def unify(a, b, sub=None):
    sub = dict(sub or {})
    a, b = apply_sub(sub, a), apply_sub(sub, b)
    if a == b:
        return sub
    if isinstance(a, str) and a.startswith("?"):
        if occurs(a, b):
            return None
        sub[a] = b
        return sub
    if isinstance(b, str) and b.startswith("?"):
        return unify(b, a, sub)
    if isinstance(a, list) and isinstance(b, list) and a[0] == b[0] and len(a) == len(b):
        for x, y in zip(a[1:], b[1:]):
            sub = unify(x, y, sub)
            if sub is None:
                return None
        return sub
    return None

import unittest
from solution import unify

class Test(unittest.TestCase):
    def test_fun(self):
        s = unify(["Fun", "?a", "Int"], ["Fun", "Bool", "?b"])
        self.assertEqual(s["?a"], "Bool")
        self.assertEqual(s["?b"], "Int")
    def test_fail(self):
        self.assertIsNone(unify("Int", "Bool"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `unify(a, b)` for a tiny type language: types are strings
('Int', 'Bool') or lists ['Fun', t1, t2]. Variables are strings starting with
`?`. Return a dict substitution or None on failure. Do not need occurs-check
beyond rejecting assigning a variable to a type that contains it as a nested list.


Answer:
import re

def unused_assigns(lines):
 assigned = set()
 used = set()
 for line in lines:
 m = re.fullmatch(r"([a-z]+) = .*", line.strip())
 if m:
 assigned.add(m.group(1))
 continue
 m = re.fullmatch(r"use ([a-z]+)", line.strip())
 if m:
 used.add(m.group(1))
 return sorted(assigned - used)

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

The hidden tests in test_solution.py must pass.

import re

def unused_assigns(lines):
    assigned = set()
    used = set()
    for line in lines:
        m = re.fullmatch(r"([a-z]+) = .*", line.strip())
        if m:
            assigned.add(m.group(1))
            continue
        m = re.fullmatch(r"use ([a-z]+)", line.strip())
        if m:
            used.add(m.group(1))
    return sorted(assigned - used)

import unittest
from solution import unused_assigns

class Test(unittest.TestCase):
    def test_unused(self):
        self.assertEqual(unused_assigns(["a = 1", "b = 2", "use a"]), ["b"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `unused_assigns(lines)` for a toy language: lines are
`x = ...` or `use x`. Names are `[a-z]+`. Return sorted names assigned at
least once and never used. Later use counts.


Answer:
def google_args(docstring):
 lines = docstring.splitlines()
 out = []
 in_args = False
 for line in lines:
 if line.strip() == "Args:":
 in_args = True
 continue
 if in_args and line.strip().endswith(":") and not line.startswith(" "):
 break
 if in_args:
 stripped = line.strip()
 if ": " in stripped:
 name, desc = stripped.split(": ", 1)
 out.append((name, desc))
 return out

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

The hidden tests in test_solution.py must pass.

def google_args(docstring):
    lines = docstring.splitlines()
    out = []
    in_args = False
    for line in lines:
        if line.strip() == "Args:":
            in_args = True
            continue
        if in_args and line.strip().endswith(":") and not line.startswith(" "):
            break
        if in_args:
            stripped = line.strip()
            if ": " in stripped:
                name, desc = stripped.split(": ", 1)
                out.append((name, desc))
    return out

import unittest
from solution import google_args

class Test(unittest.TestCase):
    def test_args(self):
        doc = """Do a thing.\n\nArgs:\n    count: how many\n    name: label\n\nReturns:\n    none\n"""
        self.assertEqual(google_args(doc), [("count", "how many"), ("name", "label")])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `google_args(docstring)` extracting Args from a Google-style
docstring. Return a list of (name, description) for lines indented like
` name: desc`. Ignore other sections.


Answer:
def google_args(docstring):
 lines = docstring.splitlines()
 out = []
 in_args = False
 for line in lines:
 if line.strip() == "Args:":
 in_args = True
 continue
 if in_args and line.strip().endswith(":") and not line.startswith(" "):
 break
 if in_args:
 stripped = line.strip()
 if ": " in stripped:
 name, desc = stripped.split(": ", 1)
 out.append((name, desc))
 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_args (test_solution.Test.test_args) ... FAIL

======================================================================
FAIL: test_args (test_solution.Test.test_args)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-aslyxdgv\test_solution.py", line 7, in test_args
    self.assertEqual(google_args(doc), [("count", "how many"), ("name", "label")])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [] != [('count', 'how many'), ('name', 'label')]

Second list contains 2 additional elements.
First extra element 0:
('count', 'how many')

- []
+ [('count', 'how many'), ('name', 'label')]

----------------------------------------------------------------------
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 `google_args(docstring)` extracting Args from a Google-style
docstring. Return a list of (name, description) for lines indented like
` name: desc`. Ignore other sections.

--- solution.py (buggy) ---
def google_args(docstring):
 lines = docstring.splitlines()
 out = []
 in_args = False
 for line in lines:
 if line.strip() != "Args:":
 in_args = True
 continue
 if in_args and line.strip().endswith(":") and not line.startswith(" "):
 break
 if in_args:
 stripped = line.strip()
 if ": " in stripped:
 name, desc = stripped.split(": ", 1)
 out.append((name, desc))
 return out

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

class Test(unittest.TestCase):
 def test_args(self):
 doc = """Do a thing.\n\nArgs:\n count: how many\n name: label\n\nReturns:\n none\n"""
 self.assertEqual(google_args(doc), [("count", "how many"), ("name", "label")])

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

test_args (test_solution.Test.test_args) ... FAIL

======================================================================
FAIL: test_args (test_solution.Test.test_args)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-aslyxdgv\test_solution.py", line 7, in test_args
 self.assertEqual(google_args(doc), [("count", "how many"), ("name", "label")])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Lists differ: [] != [('count', 'how many'), ('name', 'label')]

Second list contains 2 additional elements.
First extra element 0:
('count', 'how many')

- []
+ [('count', 'how many'), ('name', 'label')]

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

FAILED (failures=1)


Answer:
def migrate_v1_to_v2(payload):
 mapping = {"userName": "username", "emailAddress": "email"}
 return {mapping.get(k, k): v for k, v in payload.items()}

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

The hidden tests in test_solution.py must pass.

def migrate_v1_to_v2(payload):
    mapping = {"userName": "username", "emailAddress": "email"}
    return {mapping.get(k, k): v for k, v in payload.items()}

import unittest
from solution import migrate_v1_to_v2

class Test(unittest.TestCase):
    def test_rename(self):
        self.assertEqual(
            migrate_v1_to_v2({"userName": "a", "keep": 1}),
            {"username": "a", "keep": 1},
        )

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `migrate_v1_to_v2(payload)` renaming keys `userName`->`username`
and `emailAddress`->`email`, leaving other keys. Missing keys stay missing.


Answer:
def api_supported(client, server):
 return client[0] == server[0] and client[1] <= server[1]

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

The hidden tests in test_solution.py must pass.

def api_supported(client, server):
    return client[0] == server[0] and client[1] <= server[1]

import unittest
from solution import api_supported

class Test(unittest.TestCase):
    def test_ok(self):
        self.assertTrue(api_supported((1, 2), (1, 4)))
        self.assertFalse(api_supported((1, 5), (1, 4)))
        self.assertFalse(api_supported((2, 0), (1, 9)))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `api_supported(client, server)` where versions are (major, minor).
Compatible iff major matches and client.minor <= server.minor.


Answer:
def dockerfile_runs_as_root(text):
 user = None
 for raw in text.splitlines():
 line = raw.strip()
 if not line or line.startswith("#"):
 continue
 parts = line.split()
 if parts[0].upper() == "USER":
 user = parts[1] if len(parts) > 1 else ""
 if user is None:
 return True
 return user.lower() == "root" or user == "0"

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

The hidden tests in test_solution.py must pass.

def dockerfile_runs_as_root(text):
    user = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split()
        if parts[0].upper() == "USER":
            user = parts[1] if len(parts) > 1 else ""
    if user is None:
        return True
    return user.lower() == "root" or user == "0"

import unittest
from solution import dockerfile_runs_as_root

class Test(unittest.TestCase):
    def test_last_user(self):
        text = "FROM alpine\nUSER root\nUSER app\n"
        self.assertFalse(dockerfile_runs_as_root(text))
        self.assertTrue(dockerfile_runs_as_root("FROM alpine\n"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `dockerfile_runs_as_root(text)` returning True if the last
USER instruction is missing or is `USER root` / `USER 0` (ignoring case on
root). Comment lines starting with # are ignored.


Answer:
def dockerfile_runs_as_root(text):
 user = None
 for raw in text.splitlines():
 line = raw.strip()
 if not line or line.startswith("#"):
 continue
 parts = line.split()
 if parts[0].upper() == "USER":
 user = parts[1] if len(parts) > 1 else ""
 if user is None:
 return True
 return user.lower() == "root" or user == "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_last_user (test_solution.Test.test_last_user) ... FAIL

======================================================================
FAIL: test_last_user (test_solution.Test.test_last_user)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-z0hsb33r\test_solution.py", line 8, in test_last_user
    self.assertTrue(dockerfile_runs_as_root("FROM alpine\n"))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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 `dockerfile_runs_as_root(text)` returning True if the last
USER instruction is missing or is `USER root` / `USER 0` (ignoring case on
root). Comment lines starting with # are ignored.

--- solution.py (buggy) ---
def dockerfile_runs_as_root(text):
 user = None
 for raw in text.splitlines():
 line = raw.strip()
 if not line or line.startswith("#"):
 continue
 parts = line.split()
 if parts[0].upper() == "USER":
 user = parts[1] if len(parts) > 1 else ""
 if user is None:
 return False
 return user.lower() == "root" or user == "0"

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

class Test(unittest.TestCase):
 def test_last_user(self):
 text = "FROM alpine\nUSER root\nUSER app\n"
 self.assertFalse(dockerfile_runs_as_root(text))
 self.assertTrue(dockerfile_runs_as_root("FROM alpine\n"))

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

test_last_user (test_solution.Test.test_last_user) ... FAIL

======================================================================
FAIL: test_last_user (test_solution.Test.test_last_user)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-z0hsb33r\test_solution.py", line 8, in test_last_user
 self.assertTrue(dockerfile_runs_as_root("FROM alpine\n"))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

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

FAILED (failures=1)


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

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 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

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"))

Read the specification
Implement the function or class
Satisfy the tests

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