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

 def allow(self, now_s, cost=1):
 if self.t is None:
 self.t = now_s
 else:
 dt = now_s - self.t
 self.tokens = min(self.burst, self.tokens + dt * self.rate)
 self.t = now_s
 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 = None

    def allow(self, now_s, cost=1):
        if self.t is None:
            self.t = now_s
        else:
            dt = now_s - self.t
            self.tokens = min(self.burst, self.tokens + dt * self.rate)
            self.t = now_s
        if self.tokens >= cost:
            self.tokens -= cost
            return True
        return False

import unittest
from solution import TokenBucket

class Test(unittest.TestCase):
    def test_burst(self):
        b = TokenBucket(1, 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(now_s, cost=1) -> bool`.

`rate` tokens per second, `burst` max tokens. Start full. `now_s` is a
nondecreasing float clock. Fractional tokens are allowed. Deny if cost exceeds
available after refill.


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

 def allow(self, now_s, cost=1):
 if self.t is None:
 self.t = now_s
 else:
 dt = now_s - self.t
 self.tokens = min(self.burst, self.tokens + dt * self.rate)
 self.t = now_s
 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 (test_solution.Test.test_burst) ... FAIL

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

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

FAILED (failures=1)

Never refills; only counts total allows against burst.

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(now_s, cost=1) -> bool`.

`rate` tokens per second, `burst` max tokens. Start full. `now_s` is a
nondecreasing float clock. Fractional tokens are allowed. Deny if cost exceeds
available after refill.

--- solution.py (buggy) ---
class TokenBucket:
 def __init__(self, rate, burst):
 self.burst = burst
 self.n = 0

 def allow(self, now_s, cost=1):
 self.n += cost
 return self.n <= self.burst

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

class Test(unittest.TestCase):
 def test_burst(self):
 b = TokenBucket(1, 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 (test_solution.Test.test_burst) ... FAIL

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

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

FAILED (failures=1)

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


Answer:
def rle(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 n = 1
 for ch in text[1:]:
 if ch == prev:
 n += 1
 else:
 out.append(f"{prev}{n}")
 prev, n = ch, 1
 out.append(f"{prev}{n}")
 return "".join(out)

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

The hidden tests in test_solution.py must pass.

def rle(text):
    if not text:
        return ""
    out = []
    prev = text[0]
    n = 1
    for ch in text[1:]:
        if ch == prev:
            n += 1
        else:
            out.append(f"{prev}{n}")
            prev, n = ch, 1
    out.append(f"{prev}{n}")
    return "".join(out)

import unittest
from solution import rle

class Test(unittest.TestCase):
    def test_runs(self):
        self.assertEqual(rle("aaabbc"), "a3b2c1")
    def test_empty(self):
        self.assertEqual(rle(""), "")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `rle(text: str) -> str` run-length encoding: groups of
repeated characters become `{char}{count}` with count always written, even if 1.
Empty string → empty string.

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


Answer:
def rle(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 n = 1
 for ch in text[1:]:
 if ch == prev:
 n += 1
 else:
 out.append(f"{prev}{n}")
 prev, n = ch, 1
 out.append(f"{prev}{n}")
 return "".join(out)

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_empty (test_solution.Test.test_empty) ... ok
test_runs (test_solution.Test.test_runs) ... FAIL

======================================================================
FAIL: test_runs (test_solution.Test.test_runs)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-mp0kzw33\test_solution.py", line 6, in test_runs
    self.assertEqual(rle("aaabbc"), "a3b2c1")
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 'a1a1a4' != 'a3b2c1'
- a1a1a4
+ a3b2c1

----------------------------------------------------------------------
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 `rle(text: str) -> str` run-length encoding: groups of
repeated characters become `{char}{count}` with count always written, even if 1.
Empty string → empty string.

--- solution.py (buggy) ---
def rle(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 n = 1
 for ch in text[1:]:
 if ch != prev:
 n += 1
 else:
 out.append(f"{prev}{n}")
 prev, n = ch, 1
 out.append(f"{prev}{n}")
 return "".join(out)

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

class Test(unittest.TestCase):
 def test_runs(self):
 self.assertEqual(rle("aaabbc"), "a3b2c1")
 def test_empty(self):
 self.assertEqual(rle(""), "")

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

test_empty (test_solution.Test.test_empty) ... ok
test_runs (test_solution.Test.test_runs) ... FAIL

======================================================================
FAIL: test_runs (test_solution.Test.test_runs)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-mp0kzw33\test_solution.py", line 6, in test_runs
 self.assertEqual(rle("aaabbc"), "a3b2c1")
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 'a1a1a4' != 'a3b2c1'
- a1a1a4
+ a3b2c1

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

FAILED (failures=1)


Answer:
from collections import Counter

def same_multiset(a, b):
 return Counter(a) == Counter(b)

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

The hidden tests in test_solution.py must pass.

from collections import Counter

def same_multiset(a, b):
    return Counter(a) == Counter(b)

import unittest
from solution import same_multiset

class Test(unittest.TestCase):
    def test_yes(self):
        self.assertTrue(same_multiset("abba", "baba"))
    def test_no(self):
        self.assertFalse(same_multiset("ab", "a"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `same_multiset(a: str, b: str) -> bool`: True iff a and b
contain the same characters with the same frequencies (anagrams).


Answer:
from collections import Counter

def same_multiset(a, b):
 return Counter(a) == Counter(b)

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_no (test_solution.Test.test_no) ... FAIL
test_yes (test_solution.Test.test_yes) ... FAIL

======================================================================
FAIL: test_no (test_solution.Test.test_no)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-79p09q0a\test_solution.py", line 8, in test_no
    self.assertFalse(same_multiset("ab", "a"))
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True is not false

======================================================================
FAIL: test_yes (test_solution.Test.test_yes)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-79p09q0a\test_solution.py", line 6, in test_yes
    self.assertTrue(same_multiset("abba", "baba"))
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

----------------------------------------------------------------------
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 `same_multiset(a: str, b: str) -> bool`: True iff a and b
contain the same characters with the same frequencies (anagrams).

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

def same_multiset(a, b):
 return Counter(a) != Counter(b)

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

class Test(unittest.TestCase):
 def test_yes(self):
 self.assertTrue(same_multiset("abba", "baba"))
 def test_no(self):
 self.assertFalse(same_multiset("ab", "a"))

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

test_no (test_solution.Test.test_no) ... FAIL
test_yes (test_solution.Test.test_yes) ... FAIL

======================================================================
FAIL: test_no (test_solution.Test.test_no)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-79p09q0a\test_solution.py", line 8, in test_no
 self.assertFalse(same_multiset("ab", "a"))
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True is not false

======================================================================
FAIL: test_yes (test_solution.Test.test_yes)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-79p09q0a\test_solution.py", line 6, in test_yes
 self.assertTrue(same_multiset("abba", "baba"))
 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False is not true

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

FAILED (failures=2)


Answer:
def moving_avg(xs, k):
 if k <= 0:
 raise ValueError("k")
 if k > len(xs):
 return []
 out = []
 s = sum(xs[:k])
 out.append(s / k)
 for i in range(k, len(xs)):
 s += xs[i] - xs[i - k]
 out.append(s / k)
 return out

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

The hidden tests in test_solution.py must pass.

def moving_avg(xs, k):
    if k <= 0:
        raise ValueError("k")
    if k > len(xs):
        return []
    out = []
    s = sum(xs[:k])
    out.append(s / k)
    for i in range(k, len(xs)):
        s += xs[i] - xs[i - k]
        out.append(s / k)
    return out

import unittest
from solution import moving_avg

class Test(unittest.TestCase):
    def test_win(self):
        self.assertEqual(moving_avg([1, 2, 3, 4], 2), [1.5, 2.5, 3.5])
    def test_too_big(self):
        self.assertEqual(moving_avg([1], 3), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `moving_avg(xs: list[float], k: int) -> list[float]`.
Return simple moving averages of window k (k>=1). Output length is
len(xs)-k+1, or [] if k > len(xs).


Answer:
def clamp(x, lo, hi):
 if lo > hi:
 raise ValueError("range")
 return max(lo, min(hi, x))

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

The hidden tests in test_solution.py must pass.

def clamp(x, lo, hi):
    if lo > hi:
        raise ValueError("range")
    return max(lo, min(hi, x))

import unittest
from solution import clamp

class Test(unittest.TestCase):
    def test_mid(self):
        self.assertEqual(clamp(5, 0, 10), 5)
    def test_lo(self):
        self.assertEqual(clamp(-1, 0, 10), 0)
    def test_hi(self):
        self.assertEqual(clamp(99, 0, 10), 10)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `clamp(x: int, lo: int, hi: int) -> int` with lo <= hi.

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


Answer:
def rotate_left(xs, k):
 n = len(xs)
 if n == 0:
 return []
 k = k % n
 return xs[k:] + xs[:k]

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

The hidden tests in test_solution.py must pass.

def rotate_left(xs, k):
    n = len(xs)
    if n == 0:
        return []
    k = k % n
    return xs[k:] + xs[:k]

import unittest
from solution import rotate_left

class Test(unittest.TestCase):
    def test_rot(self):
        self.assertEqual(rotate_left([1, 2, 3, 4], 1), [2, 3, 4, 1])
    def test_k_big(self):
        self.assertEqual(rotate_left([1, 2], 3), [2, 1])
    def test_empty(self):
        self.assertEqual(rotate_left([], 4), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `rotate_left(xs: list, k: int) -> list` rotating a copy
left by k positions (k may be larger than len(xs); empty list stays empty).

test_empty (test_solution.Test.test_empty) ... ok
test_k_big (test_solution.Test.test_k_big) ... ok
test_rot (test_solution.Test.test_rot) ... ok

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

OK


Answer:
def rotate_left(xs, k):
 n = len(xs)
 if n == 0:
 return []
 k = k % n
 return xs[k:] + xs[:k]

Do not weaken or delete tests
Keep the public API

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

test_empty (test_solution.Test.test_empty) ... ERROR
test_k_big (test_solution.Test.test_k_big) ... FAIL
test_rot (test_solution.Test.test_rot) ... FAIL

======================================================================
ERROR: test_empty (test_solution.Test.test_empty)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\test_solution.py", line 10, in test_empty
    self.assertEqual(rotate_left([], 4), [])
                     ~~~~~~~~~~~^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\solution.py", line 5, in rotate_left
    k = k % n
        ~~^~~
ZeroDivisionError: integer modulo by zero

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

Second list contains 2 additional elements.
First extra element 0:
2

- []
+ [2, 1]

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

Second list contains 4 additional elements.
First extra element 0:
2

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

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

FAILED (failures=2, errors=1)

test_empty (test_solution.Test.test_empty) ... ERROR
test_k_big (test_solution.Test.test_k_big) ... FAIL
test_rot (test_solution.Test.test_rot) ... FAIL

======================================================================
ERROR: test_empty (test_solution.Test.test_empty)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\test_solution.py", line 10, in test_empty
    self.assertEqual(rotate_left([], 4), [])
                     ~~~~~~~~~~~^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\solution.py", line 5, in rotate_left
    k = k % n
        ~~^~~
ZeroDivisionError: integer modulo by zero

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

Second list contains 2 additional elements.
First extra element 0:
2

- []
+ [2, 1]

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

Second list contains 4 additional elements.
First extra element 0:
2

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

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

FAILED (failures=2, 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 `rotate_left(xs: list, k: int) -> list` rotating a copy
left by k positions (k may be larger than len(xs); empty list stays empty).

--- solution.py (buggy) ---
def rotate_left(xs, k):
 n = len(xs)
 if n != 0:
 return []
 k = k % n
 return xs[k:] + xs[:k]

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

class Test(unittest.TestCase):
 def test_rot(self):
 self.assertEqual(rotate_left([1, 2, 3, 4], 1), [2, 3, 4, 1])
 def test_k_big(self):
 self.assertEqual(rotate_left([1, 2], 3), [2, 1])
 def test_empty(self):
 self.assertEqual(rotate_left([], 4), [])

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

test_empty (test_solution.Test.test_empty) ... ERROR
test_k_big (test_solution.Test.test_k_big) ... FAIL
test_rot (test_solution.Test.test_rot) ... FAIL

======================================================================
ERROR: test_empty (test_solution.Test.test_empty)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\test_solution.py", line 10, in test_empty
 self.assertEqual(rotate_left([], 4), [])
 ~~~~~~~~~~~^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-km6nzd_j\solution.py", line 5, in rotate_left
 k = k % n
 ~~^~~
ZeroDivisionError: integer modulo by zero

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

Second list contains 2 additional elements.
First extra element 0:
2

- []
+ [2, 1]

======================================================================
FA


Answer:
def max_paren_depth(text):
 depth = 0
 best = 0
 for ch in text:
 if ch == "(":
 depth += 1
 best = max(best, depth)
 elif ch == ")":
 depth -= 1
 if depth < 0:
 return -1
 return best if depth == 0 else -1

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

The hidden tests in test_solution.py must pass.

def max_paren_depth(text):
    depth = 0
    best = 0
    for ch in text:
        if ch == "(":
            depth += 1
            best = max(best, depth)
        elif ch == ")":
            depth -= 1
            if depth < 0:
                return -1
    return best if depth == 0 else -1

import unittest
from solution import max_paren_depth

class Test(unittest.TestCase):
    def test_nested(self):
        self.assertEqual(max_paren_depth("(a(b))"), 2)
    def test_bad(self):
        self.assertEqual(max_paren_depth(")("), -1)
    def test_open(self):
        self.assertEqual(max_paren_depth("("), -1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `max_paren_depth(text: str) -> int` for `()` only.
Ignore other characters. Return -1 if the string is unbalanced.

test_bad (test_solution.Test.test_bad) ... ok
test_nested (test_solution.Test.test_nested) ... ok
test_open (test_solution.Test.test_open) ... ok

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

OK


Answer:
def max_paren_depth(text):
 depth = 0
 best = 0
 for ch in text:
 if ch == "(":
 depth += 1
 best = max(best, depth)
 elif ch == ")":
 depth -= 1
 if depth < 0:
 return -1
 return best if depth == 0 else -1

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_nested (test_solution.Test.test_nested) ... FAIL
test_open (test_solution.Test.test_open) ... FAIL

======================================================================
FAIL: test_nested (test_solution.Test.test_nested)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-r_zvs_bh\test_solution.py", line 6, in test_nested
    self.assertEqual(max_paren_depth("(a(b))"), 2)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 2

======================================================================
FAIL: test_open (test_solution.Test.test_open)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-r_zvs_bh\test_solution.py", line 10, in test_open
    self.assertEqual(max_paren_depth("("), -1)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != -1

----------------------------------------------------------------------
Ran 3 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 `max_paren_depth(text: str) -> int` for `()` only.
Ignore other characters. Return -1 if the string is unbalanced.

--- solution.py (buggy) ---
def max_paren_depth(text):
 depth = 0
 best = 0
 for ch in text:
 if ch != "(":
 depth += 1
 best = max(best, depth)
 elif ch == ")":
 depth -= 1
 if depth < 0:
 return -1
 return best if depth == 0 else -1

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

class Test(unittest.TestCase):
 def test_nested(self):
 self.assertEqual(max_paren_depth("(a(b))"), 2)
 def test_bad(self):
 self.assertEqual(max_paren_depth(")("), -1)
 def test_open(self):
 self.assertEqual(max_paren_depth("("), -1)

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

test_bad (test_solution.Test.test_bad) ... ok
test_nested (test_solution.Test.test_nested) ... FAIL
test_open (test_solution.Test.test_open) ... FAIL

======================================================================
FAIL: test_nested (test_solution.Test.test_nested)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-r_zvs_bh\test_solution.py", line 6, in test_nested
 self.assertEqual(max_paren_depth("(a(b))"), 2)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 2

======================================================================
FAIL: test_open (test_solution.Test.test_open)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-r_zvs_bh\test_solution.py", line 10, in test_open
 self.assertEqual(max_paren_depth("("), -1)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 0 != -1

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

FAILED (failures=2)


Answer:
from collections import Counter

def mode_int(xs):
 if not xs:
 raise ValueError("empty")
 counts = Counter(xs)
 best = max(counts.values())
 return min(v for v, c in counts.items() if c == best)

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

The hidden tests in test_solution.py must pass.

from collections import Counter

def mode_int(xs):
    if not xs:
        raise ValueError("empty")
    counts = Counter(xs)
    best = max(counts.values())
    return min(v for v, c in counts.items() if c == best)

import unittest
from solution import mode_int

class Test(unittest.TestCase):
    def test_mode(self):
        self.assertEqual(mode_int([1, 2, 2, 3]), 2)
    def test_tie(self):
        self.assertEqual(mode_int([1, 1, 2, 2]), 1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `mode_int(xs: list[int]) -> int` returning the unique
smallest mode if several values share the top frequency.


Answer:
from collections import Counter

def mode_int(xs):
 if not xs:
 raise ValueError("empty")
 counts = Counter(xs)
 best = max(counts.values())
 return min(v for v, c in counts.items() if c == best)

Do not weaken or delete tests
Keep the public API

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

test_mode (test_solution.Test.test_mode) ... FAIL
test_tie (test_solution.Test.test_tie) ... ERROR

======================================================================
ERROR: test_tie (test_solution.Test.test_tie)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-9ktkp4i2\test_solution.py", line 8, in test_tie
    self.assertEqual(mode_int([1, 1, 2, 2]), 1)
                     ~~~~~~~~^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-9ktkp4i2\solution.py", line 8, in mode_int
    return min(v for v, c in counts.items() if c != best)
ValueError: min() iterable argument is empty

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

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

FAILED (failures=1, errors=1)

Seeded mutation of the reference implementation.

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

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

Implement `mode_int(xs: list[int]) -> int` returning the unique
smallest mode if several values share the top frequency.

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

def mode_int(xs):
 if not xs:
 raise ValueError("empty")
 counts = Counter(xs)
 best = max(counts.values())
 return min(v for v, c in counts.items() if c != best)

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

class Test(unittest.TestCase):
 def test_mode(self):
 self.assertEqual(mode_int([1, 2, 2, 3]), 2)
 def test_tie(self):
 self.assertEqual(mode_int([1, 1, 2, 2]), 1)

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

test_mode (test_solution.Test.test_mode) ... FAIL
test_tie (test_solution.Test.test_tie) ... ERROR

======================================================================
ERROR: test_tie (test_solution.Test.test_tie)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-9ktkp4i2\test_solution.py", line 8, in test_tie
 self.assertEqual(mode_int([1, 1, 2, 2]), 1)
 ~~~~~~~~^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-9ktkp4i2\solution.py", line 8, in mode_int
 return min(v for v, c in counts.items() if c != best)
ValueError: min() iterable argument is empty

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

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

FAILED (failures=1, errors=1)


Answer:
def prefix_sums(xs):
 out = []
 s = 0
 for x in xs:
 s += x
 out.append(s)
 return out

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

The hidden tests in test_solution.py must pass.

def prefix_sums(xs):
    out = []
    s = 0
    for x in xs:
        s += x
        out.append(s)
    return out

import unittest
from solution import prefix_sums

class Test(unittest.TestCase):
    def test_ps(self):
        self.assertEqual(prefix_sums([1, 2, 3]), [1, 3, 6])
    def test_empty(self):
        self.assertEqual(prefix_sums([]), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `prefix_sums(xs: list[int]) -> list[int]` where
out[i] = xs[0]+...+xs[i].


Answer:
def to_kebab(name):
 bits = [p for part in name.split() for p in part.split("_") if p]
 return "-".join(b.lower() for b in bits)

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

The hidden tests in test_solution.py must pass.

def to_kebab(name):
    bits = [p for part in name.split() for p in part.split("_") if p]
    return "-".join(b.lower() for b in bits)

import unittest
from solution import to_kebab

class Test(unittest.TestCase):
    def test_mix(self):
        self.assertEqual(to_kebab("Hello_World x"), "hello-world-x")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `to_kebab(name: str) -> str`: split on spaces and `_`,
lowercase, join with `-`, drop empty pieces.


Answer:
def greedy_cover(universe, sets):
 remaining = set(universe)
 chosen = []
 used = set()
 while remaining:
 best_i = None
 best_gain = 0
 for i, s in enumerate(sets):
 if i in used:
 continue
 gain = len(remaining & s)
 if gain > best_gain or (gain == best_gain and best_i is not None and i < best_i and gain > 0):
 if gain > best_gain or (gain == best_gain and i < best_i):
 best_gain = gain
 best_i = i
 elif best_i is None and gain > 0:
 best_gain = gain
 best_i = i
 if best_i is None or best_gain == 0:
 break
 used.add(best_i)
 chosen.append(best_i)
 remaining -= sets[best_i]
 return chosen

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

The hidden tests in test_solution.py must pass.

def greedy_cover(universe, sets):
    remaining = set(universe)
    chosen = []
    used = set()
    while remaining:
        best_i = None
        best_gain = 0
        for i, s in enumerate(sets):
            if i in used:
                continue
            gain = len(remaining & s)
            if gain > best_gain or (gain == best_gain and best_i is not None and i < best_i and gain > 0):
                if gain > best_gain or (gain == best_gain and i < best_i):
                    best_gain = gain
                    best_i = i
            elif best_i is None and gain > 0:
                best_gain = gain
                best_i = i
        if best_i is None or best_gain == 0:
            break
        used.add(best_i)
        chosen.append(best_i)
        remaining -= sets[best_i]
    return chosen

import unittest
from solution import greedy_cover

class Test(unittest.TestCase):
    def test_simple(self):
        u = {1, 2, 3}
        sets = [{1, 2}, {2, 3}, {3}]
        got = greedy_cover(u, sets)
        self.assertTrue(set().union(*(sets[i] for i in got)) >= u)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `greedy_cover(universe: set[int], sets: list[set[int]]) -> list[int]`.

Return indices of sets chosen by greedy set cover (pick the set covering the
most remaining elements; ties → lowest index). Stop when universe is covered
or no set adds coverage.


Answer:
def isbn10_ok(code):
 compact = code.replace("-", "")
 if len(compact) != 10:
 return False
 total = 0
 for i, ch in enumerate(compact):
 if i < 9:
 if not ch.isdigit():
 return False
 total += int(ch) * (10 - i)
 else:
 if ch in "Xx":
 total += 10
 elif ch.isdigit():
 total += int(ch)
 else:
 return False
 return total % 11 == 0

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

The hidden tests in test_solution.py must pass.

def isbn10_ok(code):
    compact = code.replace("-", "")
    if len(compact) != 10:
        return False
    total = 0
    for i, ch in enumerate(compact):
        if i < 9:
            if not ch.isdigit():
                return False
            total += int(ch) * (10 - i)
        else:
            if ch in "Xx":
                total += 10
            elif ch.isdigit():
                total += int(ch)
            else:
                return False
    return total % 11 == 0

import unittest
from solution import isbn10_ok

class Test(unittest.TestCase):
    def test_known(self):
        self.assertTrue(isbn10_ok("0-306-40615-2"))
    def test_bad(self):
        self.assertFalse(isbn10_ok("0-306-40615-3"))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `isbn10_ok(code: str) -> bool`. `code` is 10 characters,
last may be X (value 10). Weighted sum d1*10+...+d10*1 must be 0 mod 11.
Ignore hyphens.


Answer:
def median_int(xs):
 if not xs:
 raise ValueError("empty")
 ys = sorted(xs)
 n = len(ys)
 mid = n // 2
 if n % 2:
 return float(ys[mid])
 return (ys[mid - 1] + ys[mid]) / 2

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

The hidden tests in test_solution.py must pass.

def median_int(xs):
    if not xs:
        raise ValueError("empty")
    ys = sorted(xs)
    n = len(ys)
    mid = n // 2
    if n % 2:
        return float(ys[mid])
    return (ys[mid - 1] + ys[mid]) / 2

import unittest
from solution import median_int

class Test(unittest.TestCase):
    def test_odd(self):
        self.assertEqual(median_int([3, 1, 2]), 2.0)
    def test_even(self):
        self.assertEqual(median_int([1, 2, 3, 4]), 2.5)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `median_int(xs: list[int]) -> float` for a non-empty list
(average the two middle values when length is even).


Answer:
def median_int(xs):
 if not xs:
 raise ValueError("empty")
 ys = sorted(xs)
 n = len(ys)
 mid = n // 2
 if n % 2:
 return float(ys[mid])
 return (ys[mid - 1] + ys[mid]) / 2

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_even (test_solution.Test.test_even) ... FAIL
test_odd (test_solution.Test.test_odd) ... ok

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

----------------------------------------------------------------------
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 `median_int(xs: list[int]) -> float` for a non-empty list
(average the two middle values when length is even).

--- solution.py (buggy) ---
def median_int(xs):
 if not xs:
 raise ValueError("empty")
 ys = sorted(xs)
 n = len(ys)
 mid = n // 2
 if n % 2:
 return float(ys[mid])
 return (ys[mid - 1] - ys[mid]) / 2

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

class Test(unittest.TestCase):
 def test_odd(self):
 self.assertEqual(median_int([3, 1, 2]), 2.0)
 def test_even(self):
 self.assertEqual(median_int([1, 2, 3, 4]), 2.5)

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

test_even (test_solution.Test.test_even) ... FAIL
test_odd (test_solution.Test.test_odd) ... ok

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

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

FAILED (failures=1)


Answer:
def join_query(base, extra):
 if "?" in base:
 path, qs = base.split("?", 1)
 pairs = {}
 if qs:
 for part in qs.split("&"):
 if not part:
 continue
 if "=" in part:
 k, v = part.split("=", 1)
 pairs[k] = v
 else:
 pairs[part] = ""
 else:
 pairs = {}
 else:
 path, pairs = base, {}
 pairs.update(extra)
 if not pairs:
 return path
 joined = "&".join(f"{k}={v}" for k, v in pairs.items())
 return path + "?" + joined

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

The hidden tests in test_solution.py must pass.

def join_query(base, extra):
    if "?" in base:
        path, qs = base.split("?", 1)
        pairs = {}
        if qs:
            for part in qs.split("&"):
                if not part:
                    continue
                if "=" in part:
                    k, v = part.split("=", 1)
                    pairs[k] = v
                else:
                    pairs[part] = ""
        else:
            pairs = {}
    else:
        path, pairs = base, {}
    pairs.update(extra)
    if not pairs:
        return path
    joined = "&".join(f"{k}={v}" for k, v in pairs.items())
    return path + "?" + joined

import unittest
from solution import join_query

class Test(unittest.TestCase):
    def test_merge(self):
        self.assertEqual(join_query("/x?a=1", {"b": "2"}), "/x?a=1&b=2")
    def test_override(self):
        self.assertEqual(join_query("/x?a=1", {"a": "9"}), "/x?a=9")
    def test_empty_extra(self):
        self.assertEqual(join_query("/x", {}), "/x")
    def test_add_q(self):
        self.assertEqual(join_query("/x", {"k": "v"}), "/x?k=v")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `join_query(base: str, extra: dict[str, str]) -> str`.

`base` is a URL path plus optional `?a=1` query. Merge `extra` key/value pairs
(already encoded, no spaces) onto the query string. Preserve existing pairs.
If `base` has no `?`, add one when extra is non-empty. Do not add a trailing
`?` when extra is empty. Keys in extra override same keys in base.

test_add_q (test_solution.Test.test_add_q) ... ok
test_empty_extra (test_solution.Test.test_empty_extra) ... ok
test_merge (test_solution.Test.test_merge) ... ok
test_override (test_solution.Test.test_override) ... ok

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

OK

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


Answer:
def join_query(base, extra):
 if "?" in base:
 path, qs = base.split("?", 1)
 pairs = {}
 if qs:
 for part in qs.split("&"):
 if not part:
 continue
 if "=" in part:
 k, v = part.split("=", 1)
 pairs[k] = v
 else:
 pairs[part] = ""
 else:
 pairs = {}
 else:
 path, pairs = base, {}
 pairs.update(extra)
 if not pairs:
 return path
 joined = "&".join(f"{k}={v}" for k, v in pairs.items())
 return path + "?" + joined

Do not weaken or delete tests
Keep the public API

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

test_add_q (test_solution.Test.test_add_q) ... ERROR
test_empty_extra (test_solution.Test.test_empty_extra) ... ok
test_merge (test_solution.Test.test_merge) ... ERROR
test_override (test_solution.Test.test_override) ... ERROR

======================================================================
ERROR: test_add_q (test_solution.Test.test_add_q)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 12, in test_add_q
    self.assertEqual(join_query("/x", {"k": "v"}), "/x?k=v")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

======================================================================
ERROR: test_merge (test_solution.Test.test_merge)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 6, in test_merge
    self.assertEqual(join_query("/x?a=1", {"b": "2"}), "/x?a=1&b=2")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

======================================================================
ERROR: test_override (test_solution.Test.test_override)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 8, in test_override
    self.assertEqual(join_query("/x?a=1", {"a": "9"}), "/x?a=9")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (errors=3)

test_add_q (test_solution.Test.test_add_q) ... ERROR
test_empty_extra (test_solution.Test.test_empty_extra) ... ok
test_merge (test_solution.Test.test_merge) ... ERROR
test_override (test_solution.Test.test_override) ... ERROR

======================================================================
ERROR: test_add_q (test_solution.Test.test_add_q)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 12, in test_add_q
    self.assertEqual(join_query("/x", {"k": "v"}), "/x?k=v")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

======================================================================
ERROR: test_merge (test_solution.Test.test_merge)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 6, in test_merge
    self.assertEqual(join_query("/x?a=1", {"b": "2"}), "/x?a=1&b=2")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

======================================================================
ERROR: test_override (test_solution.Test.test_override)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 8, in test_override
    self.assertEqual(join_query("/x?a=1", {"a": "9"}), "/x?a=9")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
    return path - "?" + joined
           ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (errors=3)

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 `join_query(base: str, extra: dict[str, str]) -> str`.

`base` is a URL path plus optional `?a=1` query. Merge `extra` key/value pairs
(already encoded, no spaces) onto the query string. Preserve existing pairs.
If `base` has no `?`, add one when extra is non-empty. Do not add a trailing
`?` when extra is empty. Keys in extra override same keys in base.

--- solution.py (buggy) ---
def join_query(base, extra):
 if "?" in base:
 path, qs = base.split("?", 1)
 pairs = {}
 if qs:
 for part in qs.split("&"):
 if not part:
 continue
 if "=" in part:
 k, v = part.split("=", 1)
 pairs[k] = v
 else:
 pairs[part] = ""
 else:
 pairs = {}
 else:
 path, pairs = base, {}
 pairs.update(extra)
 if not pairs:
 return path
 joined = "&".join(f"{k}={v}" for k, v in pairs.items())
 return path - "?" + joined

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

class Test(unittest.TestCase):
 def test_merge(self):
 self.assertEqual(join_query("/x?a=1", {"b": "2"}), "/x?a=1&b=2")
 def test_override(self):
 self.assertEqual(join_query("/x?a=1", {"a": "9"}), "/x?a=9")
 def test_empty_extra(self):
 self.assertEqual(join_query("/x", {}), "/x")
 def test_add_q(self):
 self.assertEqual(join_query("/x", {"k": "v"}), "/x?k=v")

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

test_add_q (test_solution.Test.test_add_q) ... ERROR
test_empty_extra (test_solution.Test.test_empty_extra) ... ok
test_merge (test_solution.Test.test_merge) ... ERROR
test_override (test_solution.Test.test_override) ... ERROR

======================================================================
ERROR: test_add_q (test_solution.Test.test_add_q)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 12, in test_add_q
 self.assertEqual(join_query("/x", {"k": "v"}), "/x?k=v")
 ~~~~~~~~~~^^^^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\solution.py", line 22, in join_query
 return path - "?" + joined
 ~~~~~^~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

======================================================================
ERROR: test_merge (test_solution.Test.test_merge)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5n6hdrz_\test_solution.py", line 6, in test_merge
 self.assertEqual(join_query("/x?a=1", {"b": "2"}), "/x?a=1&b=2")
 ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Te


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

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

The hidden tests in test_solution.py must pass.

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

import unittest
from solution import backoff_delays

class Test(unittest.TestCase):
    def test_three(self):
        self.assertEqual(backoff_delays(3, 0.5), [0.5, 1.0, 2.0])
    def test_zero(self):
        self.assertEqual(backoff_delays(0), [])
    def test_one(self):
        self.assertEqual(backoff_delays(1, 1.0), [1.0])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `backoff_delays(retries: int, base: float = 0.5) -> list[float]`.

Return `retries` delays: base, 2*base, 4*base, ... (exponential). retries=0
returns []. Do not cap. Inspired by typical HTTP client retry spacing.

test_one (test_solution.Test.test_one) ... ok
test_three (test_solution.Test.test_three) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

OK


Answer:
def parse_flags(argv):
 out = {"_": []}
 i = 0
 while i < len(argv):
 tok = argv[i]
 if tok.startswith("--") and len(tok) > 2:
 name = tok[2:]
 if i + 1 < len(argv) and not argv[i + 1].startswith("--"):
 out[name] = argv[i + 1]
 i += 2
 else:
 out[name] = True
 i += 1
 else:
 out["_"].append(tok)
 i += 1
 return out

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

The hidden tests in test_solution.py must pass.

def parse_flags(argv):
    out = {"_": []}
    i = 0
    while i < len(argv):
        tok = argv[i]
        if tok.startswith("--") and len(tok) > 2:
            name = tok[2:]
            if i + 1 < len(argv) and not argv[i + 1].startswith("--"):
                out[name] = argv[i + 1]
                i += 2
            else:
                out[name] = True
                i += 1
        else:
            out["_"].append(tok)
            i += 1
    return out

import unittest
from solution import parse_flags

class Test(unittest.TestCase):
    def test_pair(self):
        self.assertEqual(parse_flags(["--n", "2", "file"]), {"n": "2", "_": ["file"]})
    def test_bool(self):
        self.assertEqual(parse_flags(["--verbose"]), {"verbose": True, "_": []})
    def test_pos_only(self):
        self.assertEqual(parse_flags(["a", "b"]), {"_": ["a", "b"]})

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `parse_flags(argv: list[str]) -> dict`.

Treat tokens starting with `--` as flags. `--name value` stores value as str.
`--toggle` with no following non-flag token stores True. Positional tokens
(not after a flag) go to key `_`. Example: `['--n','2','file']` →
`{'n':'2', '_': ['file']}`.

test_bool (test_solution.Test.test_bool) ... ok
test_pair (test_solution.Test.test_pair) ... ok
test_pos_only (test_solution.Test.test_pos_only) ... ok

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

OK


Answer:
def parse_flags(argv):
 out = {"_": []}
 i = 0
 while i < len(argv):
 tok = argv[i]
 if tok.startswith("--") and len(tok) > 2:
 name = tok[2:]
 if i + 1 < len(argv) and not argv[i + 1].startswith("--"):
 out[name] = argv[i + 1]
 i += 2
 else:
 out[name] = True
 i += 1
 else:
 out["_"].append(tok)
 i += 1
 return out

Do not weaken or delete tests
Keep the public API

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

test_bool (test_solution.Test.test_bool) ... ERROR
test_pair (test_solution.Test.test_pair) ... ok
test_pos_only (test_solution.Test.test_pos_only) ... ok

======================================================================
ERROR: test_bool (test_solution.Test.test_bool)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7987u65q\test_solution.py", line 8, in test_bool
    self.assertEqual(parse_flags(["--verbose"]), {"verbose": True, "_": []})
                     ~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7987u65q\solution.py", line 8, in parse_flags
    if i - 1 < len(argv) and not argv[i + 1].startswith("--"):
                                 ~~~~^^^^^^^
IndexError: list index out of range

----------------------------------------------------------------------
Ran 3 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 `parse_flags(argv: list[str]) -> dict`.

Treat tokens starting with `--` as flags. `--name value` stores value as str.
`--toggle` with no following non-flag token stores True. Positional tokens
(not after a flag) go to key `_`. Example: `['--n','2','file']` →
`{'n':'2', '_': ['file']}`.

--- solution.py (buggy) ---
def parse_flags(argv):
 out = {"_": []}
 i = 0
 while i < len(argv):
 tok = argv[i]
 if tok.startswith("--") and len(tok) > 2:
 name = tok[2:]
 if i - 1 < len(argv) and not argv[i + 1].startswith("--"):
 out[name] = argv[i + 1]
 i += 2
 else:
 out[name] = True
 i += 1
 else:
 out["_"].append(tok)
 i += 1
 return out

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

class Test(unittest.TestCase):
 def test_pair(self):
 self.assertEqual(parse_flags(["--n", "2", "file"]), {"n": "2", "_": ["file"]})
 def test_bool(self):
 self.assertEqual(parse_flags(["--verbose"]), {"verbose": True, "_": []})
 def test_pos_only(self):
 self.assertEqual(parse_flags(["a", "b"]), {"_": ["a", "b"]})

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

test_bool (test_solution.Test.test_bool) ... ERROR
test_pair (test_solution.Test.test_pair) ... ok
test_pos_only (test_solution.Test.test_pos_only) ... ok

======================================================================
ERROR: test_bool (test_solution.Test.test_bool)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7987u65q\test_solution.py", line 8, in test_bool
 self.assertEqual(parse_flags(["--verbose"]), {"verbose": True, "_": []})
 ~~~~~~~~~~~^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7987u65q\solution.py", line 8, in parse_flags
 if i - 1 < len(argv) and not argv[i + 1].startswith("--"):
 ~~~~^^^^^^^
IndexError: list index out of range

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

FAILED (errors=1)


Answer:
def merge_headers(*maps):
 order = []
 lower = {}
 for mapping in maps:
 for key, value in mapping.items():
 lk = key.lower()
 if lk in lower:
 order.remove(lower[lk][0])
 lower[lk] = (key, value)
 order.append(key)
 return {k: lower[k.lower()][1] for k in order}

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

The hidden tests in test_solution.py must pass.

def merge_headers(*maps):
    order = []
    lower = {}
    for mapping in maps:
        for key, value in mapping.items():
            lk = key.lower()
            if lk in lower:
                order.remove(lower[lk][0])
            lower[lk] = (key, value)
            order.append(key)
    return {k: lower[k.lower()][1] for k in order}

import unittest
from solution import merge_headers

class Test(unittest.TestCase):
    def test_override_case(self):
        got = merge_headers({"Accept": "a"}, {"accept": "b"})
        self.assertEqual(list(got.values()), ["b"])
        self.assertEqual(len(got), 1)
    def test_keep(self):
        got = merge_headers({"A": "1"}, {"B": "2"})
        self.assertEqual(got["A"], "1")
        self.assertEqual(got["B"], "2")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `merge_headers(*maps: dict[str, str]) -> dict[str, str]`.

Later maps override earlier ones. Header names are compared case-insensitively
but the **last seen original casing** is kept as the key. Values are strings.


Answer:
def iter_chunks(data, size):
 if size <= 0:
 raise ValueError("size")
 return [data[i:i + size] for i in range(0, len(data), size)]

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

The hidden tests in test_solution.py must pass.

def iter_chunks(data, size):
    if size <= 0:
        raise ValueError("size")
    return [data[i:i + size] for i in range(0, len(data), size)]

import unittest
from solution import iter_chunks

class Test(unittest.TestCase):
    def test_split(self):
        self.assertEqual(iter_chunks(b"abcdef", 2), [b"ab", b"cd", b"ef"])
    def test_short(self):
        self.assertEqual(iter_chunks(b"ab", 5), [b"ab"])
    def test_empty(self):
        self.assertEqual(iter_chunks(b"", 3), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `iter_chunks(data: bytes, size: int) -> list[bytes]`.

Split `data` into consecutive chunks of at most `size` bytes. size must be > 0.
Empty data returns []. Last chunk may be shorter.

test_empty (test_solution.Test.test_empty) ... ok
test_short (test_solution.Test.test_short) ... ok
test_split (test_solution.Test.test_split) ... ok

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

OK


Answer:
def flag_or_env(flag, env, default):
 for item in (flag, env):
 if item is not None and item.strip():
 return item
 return default

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

The hidden tests in test_solution.py must pass.

def flag_or_env(flag, env, default):
    for item in (flag, env):
        if item is not None and item.strip():
            return item
    return default

import unittest
from solution import flag_or_env

class Test(unittest.TestCase):
    def test_flag(self):
        self.assertEqual(flag_or_env("a", "b", "c"), "a")
    def test_env(self):
        self.assertEqual(flag_or_env("  ", "b", "c"), "b")
    def test_default(self):
        self.assertEqual(flag_or_env(None, None, "c"), "c")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `flag_or_env(flag: str | None, env: str | None, default: str) -> str`.

Precedence: non-empty flag, else non-empty env, else default. Whitespace-only
counts as empty.

test_default (test_solution.Test.test_default) ... ok
test_env (test_solution.Test.test_env) ... ok
test_flag (test_solution.Test.test_flag) ... ok

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

OK


Answer:
def safe_urljoin(base, path):
 if not path:
 return base
 if path.startswith("/"):
 if "://" in base:
 scheme, rest = base.split("://", 1)
 host = rest.split("/", 1)[0]
 return f"{scheme}://{host}{path}"
 return path
 if base.endswith("/"):
 return base + path
 return base + "/" + path

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

The hidden tests in test_solution.py must pass.

def safe_urljoin(base, path):
    if not path:
        return base
    if path.startswith("/"):
        if "://" in base:
            scheme, rest = base.split("://", 1)
            host = rest.split("/", 1)[0]
            return f"{scheme}://{host}{path}"
        return path
    if base.endswith("/"):
        return base + path
    return base + "/" + path

import unittest
from solution import safe_urljoin

class Test(unittest.TestCase):
    def test_rel(self):
        self.assertEqual(safe_urljoin("https://ex/a", "b"), "https://ex/a/b")
    def test_abs(self):
        self.assertEqual(safe_urljoin("https://ex/a/b", "/z"), "https://ex/z")
    def test_slash(self):
        self.assertEqual(safe_urljoin("https://ex/a/", "b"), "https://ex/a/b")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `safe_urljoin(base: str, path: str) -> str`.

If path is empty, return base without a trailing slash unless base is exactly
a scheme host like `https://ex`. If path starts with `/`, replace the path
portion of base. Otherwise append path to base, inserting `/` if needed.

test_abs (test_solution.Test.test_abs) ... ok
test_rel (test_solution.Test.test_rel) ... ok
test_slash (test_solution.Test.test_slash) ... ok

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

OK


Answer:
def safe_urljoin(base, path):
 if not path:
 return base
 if path.startswith("/"):
 if "://" in base:
 scheme, rest = base.split("://", 1)
 host = rest.split("/", 1)[0]
 return f"{scheme}://{host}{path}"
 return path
 if base.endswith("/"):
 return base + path
 return base + "/" + path

Do not weaken or delete tests
Keep the public API

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

test_abs (test_solution.Test.test_abs) ... ok
test_rel (test_solution.Test.test_rel) ... ok
test_slash (test_solution.Test.test_slash) ... ERROR

======================================================================
ERROR: test_slash (test_solution.Test.test_slash)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-bn8accnf\test_solution.py", line 10, in test_slash
    self.assertEqual(safe_urljoin("https://ex/a/", "b"), "https://ex/a/b")
                     ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-bn8accnf\solution.py", line 11, in safe_urljoin
    return base - path
           ~~~~~^~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

----------------------------------------------------------------------
Ran 3 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 `safe_urljoin(base: str, path: str) -> str`.

If path is empty, return base without a trailing slash unless base is exactly
a scheme host like `https://ex`. If path starts with `/`, replace the path
portion of base. Otherwise append path to base, inserting `/` if needed.

--- solution.py (buggy) ---
def safe_urljoin(base, path):
 if not path:
 return base
 if path.startswith("/"):
 if "://" in base:
 scheme, rest = base.split("://", 1)
 host = rest.split("/", 1)[0]
 return f"{scheme}://{host}{path}"
 return path
 if base.endswith("/"):
 return base - path
 return base + "/" + path

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

class Test(unittest.TestCase):
 def test_rel(self):
 self.assertEqual(safe_urljoin("https://ex/a", "b"), "https://ex/a/b")
 def test_abs(self):
 self.assertEqual(safe_urljoin("https://ex/a/b", "/z"), "https://ex/z")
 def test_slash(self):
 self.assertEqual(safe_urljoin("https://ex/a/", "b"), "https://ex/a/b")

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

test_abs (test_solution.Test.test_abs) ... ok
test_rel (test_solution.Test.test_rel) ... ok
test_slash (test_solution.Test.test_slash) ... ERROR

======================================================================
ERROR: test_slash (test_solution.Test.test_slash)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-bn8accnf\test_solution.py", line 10, in test_slash
 self.assertEqual(safe_urljoin("https://ex/a/", "b"), "https://ex/a/b")
 ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-bn8accnf\solution.py", line 11, in safe_urljoin
 return base - path
 ~~~~~^~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

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

FAILED (errors=1)


Answer:
def add_tag(tag, bucket=None):
 if bucket is None:
 bucket = []
 bucket.append(tag)
 return bucket

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

The hidden tests in test_solution.py must pass.

def add_tag(tag, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(tag)
    return bucket

import unittest
from solution import add_tag

class Test(unittest.TestCase):
    def test_independent(self):
        a = add_tag("x")
        b = add_tag("y")
        self.assertEqual(a, ["x"])
        self.assertEqual(b, ["y"])
    def test_reuse(self):
        acc = []
        add_tag("a", acc)
        add_tag("b", acc)
        self.assertEqual(acc, ["a", "b"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `add_tag(tag: str, bucket: list[str] | None = None) -> list[str]`.

Append tag to a **new** list when bucket is None. Never use a shared mutable
default. Return the list.

test_independent (test_solution.Test.test_independent) ... ok
test_reuse (test_solution.Test.test_reuse) ... ok

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

OK


Answer:
def make_multipliers(n):
 return [lambda x, i=i: i * x for i in range(n)]

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

The hidden tests in test_solution.py must pass.

def make_multipliers(n):
    return [lambda x, i=i: i * x for i in range(n)]

import unittest
from solution import make_multipliers

class Test(unittest.TestCase):
    def test_bind(self):
        fns = make_multipliers(3)
        self.assertEqual([fn(2) for fn in fns], [0, 2, 4])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `make_multipliers(n: int) -> list`.

Return n functions f_i where f_i(x) == i * x for i in 0..n-1. Bind i at
definition time so later loop variables cannot change earlier closures.


Answer:
def same_object(a, b):
 return a is b

def same_value(a, b):
 return a == b

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

The hidden tests in test_solution.py must pass.

def same_object(a, b):
    return a is b

def same_value(a, b):
    return a == b

import unittest
from solution import same_object, same_value

class Test(unittest.TestCase):
    def test_alias(self):
        x = []
        self.assertTrue(same_object(x, x))
        self.assertFalse(same_object([], []))
    def test_eq(self):
        self.assertTrue(same_value([1], [1]))

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `same_object(a, b) -> bool` using identity, and
`same_value(a, b) -> bool` using equality. Do not use `is` for string/int value
comparisons inside same_value.


Answer:
def same_object(a, b):
 return a is b

def same_value(a, b):
 return a == b

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_alias (test_solution.Test.test_alias) ... ok
test_eq (test_solution.Test.test_eq) ... FAIL

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

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

FAILED (failures=1)

Seeded mutation of the reference implementation.

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

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

Implement `same_object(a, b) -> bool` using identity, and
`same_value(a, b) -> bool` using equality. Do not use `is` for string/int value
comparisons inside same_value.

--- solution.py (buggy) ---
def same_object(a, b):
 return a is b

def same_value(a, b):
 return a != b

--- test_solution.py ---
import unittest
from solution import same_object, same_value

class Test(unittest.TestCase):
 def test_alias(self):
 x = []
 self.assertTrue(same_object(x, x))
 self.assertFalse(same_object([], []))
 def test_eq(self):
 self.assertTrue(same_value([1], [1]))

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

test_alias (test_solution.Test.test_alias) ... ok
test_eq (test_solution.Test.test_eq) ... FAIL

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

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

FAILED (failures=1)


Answer:
def shallow_copy(xs):
 return list(xs)

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

The hidden tests in test_solution.py must pass.

def shallow_copy(xs):
    return list(xs)

import unittest
from solution import shallow_copy

class Test(unittest.TestCase):
    def test_new(self):
        a = [1, 2]
        b = shallow_copy(a)
        b.append(3)
        self.assertEqual(a, [1, 2])
        self.assertEqual(b, [1, 2, 3])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `shallow_copy(xs: list) -> list` that is a new list with
the same elements (shallow). Mutating the copy's slots must not change the
original's length or slot identities for immutables.

Solution:
def shallow_copy(xs):
 return list(xs)


Answer:
def chunks_needed(n, size):
 if size <= 0:
 raise ValueError("size")
 return (n + size - 1) // size

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

The hidden tests in test_solution.py must pass.

def chunks_needed(n, size):
    if size <= 0:
        raise ValueError("size")
    return (n + size - 1) // size

import unittest
from solution import chunks_needed

class Test(unittest.TestCase):
    def test_exact(self):
        self.assertEqual(chunks_needed(10, 5), 2)
    def test_ceil(self):
        self.assertEqual(chunks_needed(11, 5), 3)
    def test_zero(self):
        self.assertEqual(chunks_needed(0, 5), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `chunks_needed(n: int, size: int) -> int`.

How many blocks of `size` are needed to cover n items? size > 0. Use
ceiling division without floating point.

test_ceil (test_solution.Test.test_ceil) ... ok
test_exact (test_solution.Test.test_exact) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

OK


Answer:
def utf8_nbytes(text):
 return len(text.encode("utf-8"))

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

The hidden tests in test_solution.py must pass.

def utf8_nbytes(text):
    return len(text.encode("utf-8"))

import unittest
from solution import utf8_nbytes

class Test(unittest.TestCase):
    def test_ascii(self):
        self.assertEqual(utf8_nbytes("ab"), 2)
    def test_emoji(self):
        self.assertGreater(utf8_nbytes("é"), 1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `utf8_nbytes(text: str) -> int`: number of bytes in the
UTF-8 encoding of text.


Answer:
import re

def bind_where(column, value):
 if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", column):
 raise ValueError("column")
 return f"{column} = ?", (value,)

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

The hidden tests in test_solution.py must pass.

import re

def bind_where(column, value):
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", column):
        raise ValueError("column")
    return f"{column} = ?", (value,)

import unittest
from solution import bind_where

class Test(unittest.TestCase):
    def test_ok(self):
        sql, params = bind_where("name", "O'Brien")
        self.assertEqual(sql, "name = ?")
        self.assertEqual(params, ("O'Brien",))
    def test_bad(self):
        with self.assertRaises(ValueError):
            bind_where("name;drop", "x")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `bind_where(column: str, value: str) -> tuple[str, tuple]`.

Return a parameterized fragment `col = ?` with a one-element tuple of value.
Allow only column names matching `[A-Za-z_][A-Za-z0-9_]*`. Raise ValueError
otherwise. Do not interpolate value into the SQL string.


Answer:
def last_wins(pairs):
 out = {}
 for k, v in pairs:
 out[k] = v
 return out

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

The hidden tests in test_solution.py must pass.

def last_wins(pairs):
    out = {}
    for k, v in pairs:
        out[k] = v
    return out

import unittest
from solution import last_wins

class Test(unittest.TestCase):
    def test_override(self):
        self.assertEqual(last_wins([("a", 1), ("b", 2), ("a", 9)]), {"a": 9, "b": 2})

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `last_wins(pairs: list[tuple[str, int]]) -> dict[str, int]`.

Build a dict; later pairs override earlier ones for the same key. Preserve
insertion order of first-seen keys (Python 3.7+).


Answer:
def join_posix(*parts):
 nonempty = [p for p in parts if p]
 if not nonempty:
 return ""
 lead = nonempty[0].startswith("/")
 bits = [p.strip("/") for p in nonempty if p.strip("/")]
 body = "/".join(bits)
 if lead:
 return "/" + body if body else "/"
 return body

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

The hidden tests in test_solution.py must pass.

def join_posix(*parts):
    nonempty = [p for p in parts if p]
    if not nonempty:
        return ""
    lead = nonempty[0].startswith("/")
    bits = [p.strip("/") for p in nonempty if p.strip("/")]
    body = "/".join(bits)
    if lead:
        return "/" + body if body else "/"
    return body

import unittest
from solution import join_posix

class Test(unittest.TestCase):
    def test_rel(self):
        self.assertEqual(join_posix("a", "b"), "a/b")
    def test_abs(self):
        self.assertEqual(join_posix("/var", "log"), "/var/log")
    def test_skip_empty(self):
        self.assertEqual(join_posix("a", "", "c"), "a/c")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `join_posix(*parts: str) -> str` joining with `/`.
Collapse duplicate slashes except do not try to be a full URL parser. Empty
parts are skipped. Result must not start with `/` unless the first non-empty
part did.

test_abs (test_solution.Test.test_abs) ... ok
test_rel (test_solution.Test.test_rel) ... ok
test_skip_empty (test_solution.Test.test_skip_empty) ... ok

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

OK


Answer:
def join_posix(*parts):
 nonempty = [p for p in parts if p]
 if not nonempty:
 return ""
 lead = nonempty[0].startswith("/")
 bits = [p.strip("/") for p in nonempty if p.strip("/")]
 body = "/".join(bits)
 if lead:
 return "/" + body if body else "/"
 return body

Do not weaken or delete tests
Keep the public API

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

test_abs (test_solution.Test.test_abs) ... ERROR
test_rel (test_solution.Test.test_rel) ... ok
test_skip_empty (test_solution.Test.test_skip_empty) ... ok

======================================================================
ERROR: test_abs (test_solution.Test.test_abs)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-jz8pl0qa\test_solution.py", line 8, in test_abs
    self.assertEqual(join_posix("/var", "log"), "/var/log")
                     ~~~~~~~~~~^^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-jz8pl0qa\solution.py", line 9, in join_posix
    return "/" - body if body else "/"
           ~~~~^~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

----------------------------------------------------------------------
Ran 3 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 `join_posix(*parts: str) -> str` joining with `/`.
Collapse duplicate slashes except do not try to be a full URL parser. Empty
parts are skipped. Result must not start with `/` unless the first non-empty
part did.

--- solution.py (buggy) ---
def join_posix(*parts):
 nonempty = [p for p in parts if p]
 if not nonempty:
 return ""
 lead = nonempty[0].startswith("/")
 bits = [p.strip("/") for p in nonempty if p.strip("/")]
 body = "/".join(bits)
 if lead:
 return "/" - body if body else "/"
 return body

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

class Test(unittest.TestCase):
 def test_rel(self):
 self.assertEqual(join_posix("a", "b"), "a/b")
 def test_abs(self):
 self.assertEqual(join_posix("/var", "log"), "/var/log")
 def test_skip_empty(self):
 self.assertEqual(join_posix("a", "", "c"), "a/c")

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

test_abs (test_solution.Test.test_abs) ... ERROR
test_rel (test_solution.Test.test_rel) ... ok
test_skip_empty (test_solution.Test.test_skip_empty) ... ok

======================================================================
ERROR: test_abs (test_solution.Test.test_abs)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-jz8pl0qa\test_solution.py", line 8, in test_abs
 self.assertEqual(join_posix("/var", "log"), "/var/log")
 ~~~~~~~~~~^^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-jz8pl0qa\solution.py", line 9, in join_posix
 return "/" - body if body else "/"
 ~~~~^~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'

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

FAILED (errors=1)


Answer:
def unique_stable(items):
 seen = set()
 out = []
 for item in items:
 if item in seen:
 continue
 seen.add(item)
 out.append(item)
 return out

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

The hidden tests in test_solution.py must pass.

def unique_stable(items):
    seen = set()
    out = []
    for item in items:
        if item in seen:
            continue
        seen.add(item)
        out.append(item)
    return out

import unittest
from solution import unique_stable

class Test(unittest.TestCase):
    def test_order(self):
        self.assertEqual(unique_stable(["b", "a", "b", "c"]), ["b", "a", "c"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `unique_stable(items: list) -> list` keeping first
occurrences only, preserving order.


Answer:
SELECT dept, COUNT(*) AS headcount
FROM employees
GROUP BY dept
HAVING COUNT(*) >= 2
ORDER BY headcount DESC, dept ASC;

Return exactly the specified columns and order

SELECT dept, COUNT(*) AS headcount
FROM employees
GROUP BY dept
HAVING COUNT(*) >= 2
ORDER BY headcount DESC, dept ASC;

Read the schema
Write a query
Check row order and values

Prompt:
Tables: employees(id, dept, salary). Write a SQL query that returns dept and headcount for departments with at least 2 employees, ordered by headcount descending, then dept ascending.

Schema and seed data:
CREATE TABLE employees (id INTEGER, dept TEXT, salary INTEGER);
INSERT INTO employees VALUES
 (1, 'eng', 100), (2, 'eng', 110), (3, 'eng', 90),
 (4, 'hr', 70), (5, 'sales', 80), (6, 'sales', 85);

OPEN_REASON_RESULT {"passed": true, "rows": [["eng", 3], ["sales", 2]], "expected": [["eng", 3], ["sales", 2]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT c.name, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.total >= 50
ORDER BY o.total DESC, c.name ASC;

Return exactly the specified columns and order

SELECT c.name, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.total >= 50
ORDER BY o.total DESC, c.name ASC;

Read the schema
Write a query
Check row order and values

Prompt:
customers(id, name), orders(id, customer_id, total). Return customer name and order total for orders with total >= 50, ordered by total descending.

Schema and seed data:
CREATE TABLE customers (id INTEGER, name TEXT);
CREATE TABLE orders (id INTEGER, customer_id INTEGER, total INTEGER);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cyd');
INSERT INTO orders VALUES (10, 1, 40), (11, 1, 80), (12, 2, 50), (13, 3, 10);

OPEN_REASON_RESULT {"passed": true, "rows": [["Ada", 80], ["Ben", 50]], "expected": [["Ada", 80], ["Ben", 50]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT u.name, COUNT(l.user_id) AS n
FROM users AS u
LEFT JOIN logins AS l ON l.user_id = u.id
GROUP BY u.id, u.name
ORDER BY u.name;

Return exactly the specified columns and order

SELECT u.name, COUNT(l.user_id) AS n
FROM users AS u
LEFT JOIN logins AS l ON l.user_id = u.id
GROUP BY u.id, u.name
ORDER BY u.name;

Read the schema
Write a query
Check row order and values

Prompt:
users(id, name), logins(user_id). Return each user name and their login count, including users with zero logins, ordered by name.

Schema and seed data:
CREATE TABLE users (id INTEGER, name TEXT);
CREATE TABLE logins (user_id INTEGER);
INSERT INTO users VALUES (1, 'a'), (2, 'b'), (3, 'c');
INSERT INTO logins VALUES (1), (1), (3);


Answer:
SELECT day, SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS running
FROM events
ORDER BY day;

Return exactly the specified columns and order

SELECT day, SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS running
FROM events
ORDER BY day;

Read the schema
Write a query
Check row order and values

Prompt:
events(day, amount) with one row per day. Return day and a running sum of amount ordered by day (SQLite window functions).

Schema and seed data:
CREATE TABLE events (day INTEGER, amount INTEGER);
INSERT INTO events VALUES (1, 5), (2, 3), (3, 8);


Answer:
WITH ranked AS (
 SELECT course, student, score,
 ROW_NUMBER() OVER (PARTITION BY course ORDER BY score DESC, student ASC) AS rk
 FROM scores
)
SELECT course, student, score FROM ranked WHERE rk = 1 ORDER BY course;

Return exactly the specified columns and order

WITH ranked AS (
  SELECT course, student, score,
         ROW_NUMBER() OVER (PARTITION BY course ORDER BY score DESC, student ASC) AS rk
  FROM scores
)
SELECT course, student, score FROM ranked WHERE rk = 1 ORDER BY course;

Read the schema
Write a query
Check row order and values

Prompt:
scores(student, course, score). Return the student with the highest score in each course (break ties by student name ascending). Columns: course, student, score.

Schema and seed data:
CREATE TABLE scores (student TEXT, course TEXT, score INTEGER);
INSERT INTO scores VALUES
 ('ann', 'math', 90), ('bob', 'math', 90), ('ann', 'cs', 70), ('bob', 'cs', 95);

OPEN_REASON_RESULT {"passed": true, "rows": [["cs", "bob", 95], ["math", "ann", 90]], "expected": [["cs", "bob", 95], ["math", "ann", 90]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT p.id
FROM parts AS p
WHERE NOT EXISTS (SELECT 1 FROM used u WHERE u.part_id = p.id)
ORDER BY p.id;

Return exactly the specified columns and order

SELECT p.id
FROM parts AS p
WHERE NOT EXISTS (SELECT 1 FROM used u WHERE u.part_id = p.id)
ORDER BY p.id;

Read the schema
Write a query
Check row order and values

Prompt:
parts(id), used(part_id). Return ids of parts that were never used, ordered.

Schema and seed data:
CREATE TABLE parts (id INTEGER);
CREATE TABLE used (part_id INTEGER);
INSERT INTO parts VALUES (1), (2), (3), (4);
INSERT INTO used VALUES (2), (2), (4);

OPEN_REASON_RESULT {"passed": true, "rows": [[1], [3]], "expected": [[1], [3]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT CASE
 WHEN celsius < 10 THEN 'cold'
 WHEN celsius <= 25 THEN 'mild'
 ELSE 'hot'
 END AS bucket,
 COUNT(*) AS n
FROM temps
GROUP BY bucket
ORDER BY n DESC, bucket ASC;

Return exactly the specified columns and order

SELECT CASE
         WHEN celsius < 10 THEN 'cold'
         WHEN celsius <= 25 THEN 'mild'
         ELSE 'hot'
       END AS bucket,
       COUNT(*) AS n
FROM temps
GROUP BY bucket
ORDER BY n DESC, bucket ASC;

Read the schema
Write a query
Check row order and values

Prompt:
temps(celsius). Bucket into 'cold' (<10), 'mild' [10,25], 'hot' (>25) and return bucket, n ordered by n descending, bucket ascending.

Schema and seed data:
CREATE TABLE temps (celsius INTEGER);
INSERT INTO temps VALUES (0), (5), (10), (20), (25), (30), (40);

OPEN_REASON_RESULT {"passed": true, "rows": [["mild", 3], ["cold", 2], ["hot", 2]], "expected": [["mild", 3], ["cold", 2], ["hot", 2]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT e.name AS employee, m.name AS manager
FROM staff AS e
JOIN staff AS m ON e.manager_id = m.id
ORDER BY e.name;

Return exactly the specified columns and order

SELECT e.name AS employee, m.name AS manager
FROM staff AS e
JOIN staff AS m ON e.manager_id = m.id
ORDER BY e.name;

Read the schema
Write a query
Check row order and values

Prompt:
staff(id, name, manager_id). Return employee name and manager name for employees who have a manager, ordered by employee name.

Schema and seed data:
CREATE TABLE staff (id INTEGER, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1, 'root', NULL), (2, 'lee', 1), (3, 'sam', 1), (4, 'pat', 2);

OPEN_REASON_RESULT {"passed": true, "rows": [["lee", "root"], ["pat", "lee"], ["sam", "root"]], "expected": [["lee", "root"], ["pat", "lee"], ["sam", "root"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT COUNT(DISTINCT user_id) AS n
FROM sessions
WHERE active = 1;

Return exactly the specified columns and order

SELECT COUNT(DISTINCT user_id) AS n
FROM sessions
WHERE active = 1;

Read the schema
Write a query
Check row order and values

Prompt:
sessions(user_id, active INTEGER 0/1). How many distinct users have at least one active session? Return a single column n.

Schema and seed data:
CREATE TABLE sessions (user_id INTEGER, active INTEGER);
INSERT INTO sessions VALUES (1, 0), (1, 1), (2, 0), (3, 1), (3, 1);

OPEN_REASON_RESULT {"passed": true, "rows": [[2]], "expected": [[2]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT name, CAST(julianday(ts) - julianday('2026-01-01') AS INTEGER) AS days
FROM events
ORDER BY name;

Return exactly the specified columns and order

SELECT name, CAST(julianday(ts) - julianday('2026-01-01') AS INTEGER) AS days
FROM events
ORDER BY name;

Read the schema
Write a query
Check row order and values

Prompt:
events(name, ts TEXT as YYYY-MM-DD). Return name and days since 2026-01-01 for each event (julianday difference as integer), ordered by name.

Schema and seed data:
CREATE TABLE events (name TEXT, ts TEXT);
INSERT INTO events VALUES ('a', '2026-01-11'), ('b', '2026-01-01');

OPEN_REASON_RESULT {"passed": true, "rows": [["a", 10], ["b", 0]], "expected": [["a", 10], ["b", 0]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT sku, (cents * 9) / 10 AS discounted
FROM prices
ORDER BY sku;

Return exactly the specified columns and order

SELECT sku, (cents * 9) / 10 AS discounted
FROM prices
ORDER BY sku;

Read the schema
Write a query
Check row order and values

Prompt:
prices(sku, cents). Return sku and a discounted price: 10% off using integer arithmetic (cents * 9 / 10), ordered by sku.

Schema and seed data:
CREATE TABLE prices (sku TEXT, cents INTEGER);
INSERT INTO prices VALUES ('aa', 1000), ('bb', 50);

OPEN_REASON_RESULT {"passed": true, "rows": [["aa", 900], ["bb", 45]], "expected": [["aa", 900], ["bb", 45]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT product, ROUND(AVG(stars), 2) AS avg_stars
FROM reviews
GROUP BY product
HAVING AVG(stars) >= 4.0
ORDER BY product;

Return exactly the specified columns and order

SELECT product, ROUND(AVG(stars), 2) AS avg_stars
FROM reviews
GROUP BY product
HAVING AVG(stars) >= 4.0
ORDER BY product;

Read the schema
Write a query
Check row order and values

Prompt:
reviews(product, stars). Return products whose average stars are at least 4.0, with avg_stars rounded to 2 decimals via ROUND, ordered by product.

Schema and seed data:
CREATE TABLE reviews (product TEXT, stars INTEGER);
INSERT INTO reviews VALUES ('p', 5), ('p', 4), ('q', 3), ('q', 3), ('r', 5);


Answer:
SELECT DISTINCT tag
FROM tags
ORDER BY tag;

Return exactly the specified columns and order

SELECT DISTINCT tag
FROM tags
ORDER BY tag;

Read the schema
Write a query
Check row order and values

Prompt:
tags(item, tag). Return distinct tags in alphabetical order.

Schema and seed data:
CREATE TABLE tags (item TEXT, tag TEXT);
INSERT INTO tags VALUES ('a', 'x'), ('b', 'y'), ('c', 'x'), ('d', 'z');

OPEN_REASON_RESULT {"passed": true, "rows": [["x"], ["y"], ["z"]], "expected": [["x"], ["y"], ["z"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT id,
 CASE
 WHEN n >= 80 THEN 'high'
 WHEN n >= 50 THEN 'mid'
 ELSE 'low'
 END AS band
FROM scores
ORDER BY id;

Return exactly the specified columns and order

SELECT id,
  CASE
    WHEN n >= 80 THEN 'high'
    WHEN n >= 50 THEN 'mid'
    ELSE 'low'
  END AS band
FROM scores
ORDER BY id;

Read the schema
Write a query
Check row order and values

Prompt:
scores(id, n). Return id and band where n>=80 is 'high', n>=50 is 'mid', else 'low', ordered by id.

Schema and seed data:
CREATE TABLE scores (id INTEGER, n INTEGER);
INSERT INTO scores VALUES (1, 90), (2, 50), (3, 20);

OPEN_REASON_RESULT {"passed": true, "rows": [[1, "high"], [2, "mid"], [3, "low"]], "expected": [[1, "high"], [2, "mid"], [3, "low"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT e.name AS employee, m.name AS manager
FROM staff AS e
JOIN staff AS m ON e.manager_id = m.id
ORDER BY e.name;

Return exactly the specified columns and order

Read the schema
Write a query
Check row order and values

Prompt:
staff(id, name, manager_id). Return employee name and manager name for employees who have a manager, ordered by employee name.

Schema and seed data:
CREATE TABLE staff (id INTEGER, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1, 'Ada', NULL), (2, 'Ben', 1), (3, 'Cyd', 1);

OPEN_REASON_RESULT {"passed": true, "rows": [["Ben", "Ada"], ["Cyd", "Ada"]], "expected": [["Ben", "Ada"], ["Cyd", "Ada"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT name
FROM scores
WHERE pts = (SELECT MAX(pts) FROM scores)
ORDER BY name;

Return exactly the specified columns and order

SELECT name
FROM scores
WHERE pts = (SELECT MAX(pts) FROM scores)
ORDER BY name;

Read the schema
Write a query
Check row order and values

Prompt:
scores(name, pts). Return names whose pts equal the maximum pts in the table, ordered by name.

Schema and seed data:
CREATE TABLE scores (name TEXT, pts INTEGER);
INSERT INTO scores VALUES ('Ada', 10), ('Ben', 7), ('Cyd', 10);

OPEN_REASON_RESULT {"passed": true, "rows": [["Ada"], ["Cyd"]], "expected": [["Ada"], ["Cyd"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT id, COALESCE(qty, 0) AS qty
FROM items
ORDER BY id;

Return exactly the specified columns and order

SELECT id, COALESCE(qty, 0) AS qty
FROM items
ORDER BY id;

Read the schema
Write a query
Check row order and values

Prompt:
items(id, qty) where qty may be NULL. Return id and qty with NULL qty shown as 0, ordered by id.

Schema and seed data:
CREATE TABLE items (id INTEGER, qty INTEGER);
INSERT INTO items VALUES (1, 4), (2, NULL), (3, 0);


Answer:
SELECT e.name, m.name
FROM emp AS e
JOIN emp AS m ON m.id = e.mgr_id
ORDER BY e.name;

Return exactly the specified columns and order

SELECT e.name, m.name
FROM emp AS e
JOIN emp AS m ON m.id = e.mgr_id
ORDER BY e.name;

Read the schema
Write a query
Check row order and values

Prompt:
emp(id, name, mgr_id). Return employee name and manager name for employees who have a manager, ordered by employee name.

Schema and seed data:
CREATE TABLE emp (id INTEGER, name TEXT, mgr_id INTEGER);
INSERT INTO emp VALUES (1, 'Ann', NULL), (2, 'Bea', 1), (3, 'Cal', 1);

OPEN_REASON_RESULT {"passed": true, "rows": [["Bea", "Ann"], ["Cal", "Ann"]], "expected": [["Bea", "Ann"], ["Cal", "Ann"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer: SELECT COUNT(DISTINCT user_id) AS n FROM visits;

Return exactly the specified columns and order

SELECT COUNT(DISTINCT user_id) AS n FROM visits;

Read the schema
Write a query
Check row order and values

Prompt:
visits(user_id). Return the number of distinct user_id values.

Schema and seed data:
CREATE TABLE visits (user_id INTEGER);
INSERT INTO visits VALUES (1), (1), (2), (3), (3);

OPEN_REASON_RESULT {"passed": true, "rows": [[3]], "expected": [[3]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT id,
 CASE
 WHEN pts < 50 THEN 'low'
 WHEN pts < 80 THEN 'mid'
 ELSE 'high'
 END AS band
FROM scores
ORDER BY id;

Return exactly the specified columns and order

SELECT id,
       CASE
         WHEN pts < 50 THEN 'low'
         WHEN pts < 80 THEN 'mid'
         ELSE 'high'
       END AS band
FROM scores
ORDER BY id;

Read the schema
Write a query
Check row order and values

Prompt:
scores(id, pts). Return id and a band: 'low' if pts < 50, 'mid' if pts < 80, else 'high', ordered by id.

Schema and seed data:
CREATE TABLE scores (id INTEGER, pts INTEGER);
INSERT INTO scores VALUES (1, 40), (2, 50), (3, 90);

OPEN_REASON_RESULT {"passed": true, "rows": [[1, "low"], [2, "mid"], [3, "high"]], "expected": [[1, "low"], [2, "mid"], [3, "high"]], "tests_run": 1, "failures": 0, "errors": 0}


Answer:
SELECT id FROM wanted
WHERE id NOT IN (SELECT id FROM have)
ORDER BY id;

Return exactly the specified columns and order

SELECT id FROM wanted
WHERE id NOT IN (SELECT id FROM have)
ORDER BY id;

Read the schema
Write a query
Check row order and values

Prompt:
wanted(id), have(id). Return wanted ids that are not in have, ordered by id.

Schema and seed data:
CREATE TABLE wanted (id INTEGER);
CREATE TABLE have (id INTEGER);
INSERT INTO wanted VALUES (1), (2), (3);
INSERT INTO have VALUES (2);


Answer:
SELECT course, AVG(score) AS avg_score
FROM grades
GROUP BY course
ORDER BY course;

Return exactly the specified columns and order

SELECT course, AVG(score) AS avg_score
FROM grades
GROUP BY course
ORDER BY course;

Read the schema
Write a query
Check row order and values

Prompt:
grades(course, score). Return course and average score as a real, ordered by course.

Schema and seed data:
CREATE TABLE grades (course TEXT, score INTEGER);
INSERT INTO grades VALUES ('a', 10), ('a', 20), ('b', 5);