Answer:
def n_primes(n):
 def p(x):
 if x<2: return False
 d=2
 while d*d<=x:
 if x%d==0: return False
 d+=1
 return True
 return sum(p(i) for i in range(1,n+1))

Do not weaken or delete tests
Keep the public API

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... FAIL
test_3 (test_solution.Test.test_3) ... FAIL
test_4 (test_solution.Test.test_4) ... FAIL
test_5 (test_solution.Test.test_5) ... FAIL

======================================================================
FAIL: test_2 (test_solution.Test.test_2)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 9, in test_2
    self.assertEqual(n_primes(2), 1)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
AssertionError: 0 != 1

======================================================================
FAIL: test_3 (test_solution.Test.test_3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 11, in test_3
    self.assertEqual(n_primes(10), 4)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
AssertionError: 0 != 4

======================================================================
FAIL: test_4 (test_solution.Test.test_4)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 13, in test_4
    self.assertEqual(n_primes(20), 8)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
AssertionError: 0 != 8

======================================================================
FAIL: test_5 (test_solution.Test.test_5)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 15, in test_5
    self.assertEqual(n_primes(30), 10)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
AssertionError: 0 != 10

----------------------------------------------------------------------
Ran 6 tests in 0.001s

FAILED (failures=4)

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 `n_primes`: Count primes in 1..n inclusive. Use only the Python standard library.

--- solution.py (buggy) ---
def n_primes(n):
 def p(x):
 if x<2: return False
 d=2
 while d*d<=x:
 if x%d==0: return False
 d+=1
 return False
 return sum(p(i) for i in range(1,n+1))

--- test_solution.py ---
import unittest
from solution import n_primes
class Test(unittest.TestCase):
 def test_0(self):
 self.assertEqual(n_primes(0), 0)
 def test_1(self):
 self.assertEqual(n_primes(1), 0)
 def test_2(self):
 self.assertEqual(n_primes(2), 1)
 def test_3(self):
 self.assertEqual(n_primes(10), 4)
 def test_4(self):
 self.assertEqual(n_primes(20), 8)
 def test_5(self):
 self.assertEqual(n_primes(30), 10)

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... FAIL
test_3 (test_solution.Test.test_3) ... FAIL
test_4 (test_solution.Test.test_4) ... FAIL
test_5 (test_solution.Test.test_5) ... FAIL

======================================================================
FAIL: test_2 (test_solution.Test.test_2)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 9, in test_2
 self.assertEqual(n_primes(2), 1)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
AssertionError: 0 != 1

======================================================================
FAIL: test_3 (test_solution.Test.test_3)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\test_solution.py", line 11, in test_3
 self.assertEqual(n_primes(10), 4)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
AssertionError: 0 != 4

======================================================================
FAIL: test_4 (test_solution.Test.test_4)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-5ij7ym8g\tes


Answer:
def base_conv(n,b):
 digits='0123456789abcdef'
 if n==0: return '0'
 out=[]
 while n:
 out.append(digits[n%b]); n//=b
 return ''.join(reversed(out))

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

The hidden tests in test_solution.py must pass.

def base_conv(n,b):
    digits='0123456789abcdef'
    if n==0: return '0'
    out=[]
    while n:
        out.append(digits[n%b]); n//=b
    return ''.join(reversed(out))

import unittest
from solution import base_conv
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(base_conv(0, 2), '0')
    def test_1(self):
        self.assertEqual(base_conv(5, 2), '101')
    def test_2(self):
        self.assertEqual(base_conv(255, 16), 'ff')
    def test_3(self):
        self.assertEqual(base_conv(10, 10), '10')
    def test_4(self):
        self.assertEqual(base_conv(8, 8), '10')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `base_conv`: Convert non-negative int n to base b (2..16) as a lowercase string without prefix. Use only the Python standard library.

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

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


Answer:
def parse_int_base(s,b):
 return int(s,b)

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

The hidden tests in test_solution.py must pass.

def parse_int_base(s,b):
    return int(s,b)

import unittest
from solution import parse_int_base
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(parse_int_base('1010', 2), 10)
    def test_1(self):
        self.assertEqual(parse_int_base('ff', 16), 255)
    def test_2(self):
        self.assertEqual(parse_int_base('17', 8), 15)
    def test_3(self):
        self.assertEqual(parse_int_base('0', 10), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `parse_int_base`: Parse s in base b (2..16). Use only the Python standard library.

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


Answer:
def hamming(a,b):
 if len(a)!=len(b): raise ValueError('len')
 return sum(x!=y for x,y in zip(a,b))

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

The hidden tests in test_solution.py must pass.

def hamming(a,b):
    if len(a)!=len(b): raise ValueError('len')
    return sum(x!=y for x,y in zip(a,b))

import unittest
from solution import hamming
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(hamming('karolin', 'kathrin'), 3)
    def test_1(self):
        self.assertEqual(hamming('000', '111'), 3)
    def test_2(self):
        self.assertEqual(hamming('a', 'a'), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `hamming`: Hamming distance of two equal-length strings; ValueError if lengths differ. Use only the Python standard library.

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


Answer:
def lev_one(a,b):
 if abs(len(a)-len(b))>1: return False
 if len(a)==len(b):
 return sum(x!=y for x,y in zip(a,b))<=1
 if len(a)>len(b): a,b=b,a
 i=j=diff=0
 while i<len(a) and j<len(b):
 if a[i]==b[j]:
 i+=1; j+=1
 else:
 diff+=1; j+=1
 if diff>1: return False
 return True

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

The hidden tests in test_solution.py must pass.

def lev_one(a,b):
    if abs(len(a)-len(b))>1: return False
    if len(a)==len(b):
        return sum(x!=y for x,y in zip(a,b))<=1
    if len(a)>len(b): a,b=b,a
    i=j=diff=0
    while i<len(a) and j<len(b):
        if a[i]==b[j]:
            i+=1; j+=1
        else:
            diff+=1; j+=1
            if diff>1: return False
    return True

import unittest
from solution import lev_one
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(lev_one('cat', 'cut'), True)
    def test_1(self):
        self.assertEqual(lev_one('cat', 'cats'), True)
    def test_2(self):
        self.assertEqual(lev_one('cat', 'dog'), False)
    def test_3(self):
        self.assertEqual(lev_one('a', 'a'), True)
    def test_4(self):
        self.assertEqual(lev_one('ab', 'a'), True)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `lev_one`: True iff Levenshtein distance of a,b is at most 1. Use only the Python standard library.


Answer:
def lev_one(a,b):
 if abs(len(a)-len(b))>1: return False
 if len(a)==len(b):
 return sum(x!=y for x,y in zip(a,b))<=1
 if len(a)>len(b): a,b=b,a
 i=j=diff=0
 while i<len(a) and j<len(b):
 if a[i]==b[j]:
 i+=1; j+=1
 else:
 diff+=1; j+=1
 if diff>1: return False
 return True

Do not weaken or delete tests
Keep the public API

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... FAIL
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... FAIL

======================================================================
FAIL: test_1 (test_solution.Test.test_1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ue8fkkap\test_solution.py", line 7, in test_1
    self.assertEqual(lev_one('cat', 'cats'), True)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

======================================================================
FAIL: test_4 (test_solution.Test.test_4)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ue8fkkap\test_solution.py", line 13, in test_4
    self.assertEqual(lev_one('ab', 'a'), True)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

----------------------------------------------------------------------
Ran 5 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 `lev_one`: True iff Levenshtein distance of a,b is at most 1. Use only the Python standard library.

--- solution.py (buggy) ---
def lev_one(a,b):
 if abs(len(a)-len(b))>1: return False
 if len(a)==len(b):
 return sum(x!=y for x,y in zip(a,b))<=1
 if len(a)>len(b): a,b=b,a
 i=j=diff=0
 while i<len(a) and j<len(b):
 if a[i]==b[j]:
 i+=1; j+=1
 else:
 diff+=1; j+=1
 if diff>1: return False
 return False

--- test_solution.py ---
import unittest
from solution import lev_one
class Test(unittest.TestCase):
 def test_0(self):
 self.assertEqual(lev_one('cat', 'cut'), True)
 def test_1(self):
 self.assertEqual(lev_one('cat', 'cats'), True)
 def test_2(self):
 self.assertEqual(lev_one('cat', 'dog'), False)
 def test_3(self):
 self.assertEqual(lev_one('a', 'a'), True)
 def test_4(self):
 self.assertEqual(lev_one('ab', 'a'), True)

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... FAIL
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... FAIL

======================================================================
FAIL: test_1 (test_solution.Test.test_1)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ue8fkkap\test_solution.py", line 7, in test_1
 self.assertEqual(lev_one('cat', 'cats'), True)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

======================================================================
FAIL: test_4 (test_solution.Test.test_4)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-ue8fkkap\test_solution.py", line 13, in test_4
 self.assertEqual(lev_one('ab', 'a'), True)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

----------------------------------------------------------------------
Ran 5 tests in 0.001s

FAILED (failures=2)


Answer:
import re
def balanced_html(s):
 stack=[]; i=0
 while i<len(s):
 if s.startswith('</',i):
 m=re.match(r'</([a-z]+)>', s[i:])
 if not m or not stack or stack[-1]!=m.group(1): return False
 stack.pop(); i+=m.end()
 elif s[i]=='<':
 m=re.match(r'<([a-z]+)>', s[i:])
 if not m: return False
 stack.append(m.group(1)); i+=m.end()
 else:
 i+=1
 return not stack

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

The hidden tests in test_solution.py must pass.

import re
def balanced_html(s):
    stack=[]; i=0
    while i<len(s):
        if s.startswith('</',i):
            m=re.match(r'</([a-z]+)>', s[i:])
            if not m or not stack or stack[-1]!=m.group(1): return False
            stack.pop(); i+=m.end()
        elif s[i]=='<':
            m=re.match(r'<([a-z]+)>', s[i:])
            if not m: return False
            stack.append(m.group(1)); i+=m.end()
        else:
            i+=1
    return not stack

import unittest
from solution import balanced_html
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(balanced_html('x'), True)
    def test_1(self):
        self.assertEqual(balanced_html(''), True)
    def test_2(self):
        self.assertEqual(balanced_html(''), False)
    def test_3(self):
        self.assertEqual(balanced_html('plain'), True)
    def test_4(self):
        self.assertEqual(balanced_html(''), False)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `balanced_html`: True iff every <tag> is closed by </tag> with a stack, tags [a-z]+ only, no attributes. Use only the Python standard library.


Answer:
import re
def balanced_html(s):
 stack=[]; i=0
 while i<len(s):
 if s.startswith('</',i):
 m=re.match(r'</([a-z]+)>', s[i:])
 if not m or not stack or stack[-1]!=m.group(1): return False
 stack.pop(); i+=m.end()
 elif s[i]=='<':
 m=re.match(r'<([a-z]+)>', s[i:])
 if not m: return False
 stack.append(m.group(1)); i+=m.end()
 else:
 i+=1
 return not stack

Do not weaken or delete tests
Keep the public API

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... FAIL
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok

======================================================================
FAIL: test_2 (test_solution.Test.test_2)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7jxaq2cl\test_solution.py", line 9, in test_2
    self.assertEqual(balanced_html('<b></i>'), False)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True != False

----------------------------------------------------------------------
Ran 5 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 `balanced_html`: True iff every <tag> is closed by </tag> with a stack, tags [a-z]+ only, no attributes. Use only the Python standard library.

--- solution.py (buggy) ---
import re
def balanced_html(s):
 stack=[]; i=0
 while i<len(s):
 if s.startswith('</',i):
 m=re.match(r'</([a-z]+)>', s[i:])
 if not m or not stack or stack[-1]!=m.group(1): return True
 stack.pop(); i+=m.end()
 elif s[i]=='<':
 m=re.match(r'<([a-z]+)>', s[i:])
 if not m: return False
 stack.append(m.group(1)); i+=m.end()
 else:
 i+=1
 return not stack

--- test_solution.py ---
import unittest
from solution import balanced_html
class Test(unittest.TestCase):
 def test_0(self):
 self.assertEqual(balanced_html('x'), True)
 def test_1(self):
 self.assertEqual(balanced_html(''), True)
 def test_2(self):
 self.assertEqual(balanced_html(''), False)
 def test_3(self):
 self.assertEqual(balanced_html('plain'), True)
 def test_4(self):
 self.assertEqual(balanced_html(''), False)

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

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... FAIL
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok

======================================================================
FAIL: test_2 (test_solution.Test.test_2)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-7jxaq2cl\test_solution.py", line 9, in test_2
 self.assertEqual(balanced_html(''), False)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True != False

----------------------------------------------------------------------
Ran 5 tests in 0.001s

FAILED (failures=1)


Answer:
def path_join(parts):
 s='/'.join(parts)
 while '//' in s:
 s=s.replace('//','/')
 return s

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

The hidden tests in test_solution.py must pass.

def path_join(parts):
    s='/'.join(parts)
    while '//' in s:
        s=s.replace('//','/')
    return s

import unittest
from solution import path_join
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(path_join(['a', 'b']), 'a/b')
    def test_1(self):
        self.assertEqual(path_join(['/a/', '/b']), '/a/b')
    def test_2(self):
        self.assertEqual(path_join(['a', '', 'b']), 'a/b')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `path_join`: Join POSIX-like fragments, collapsing duplicate slashes but not resolving '..' . Use only the Python standard library.


Answer:
def ext_of(name):
 i=name.rfind('.')
 if i<=0: return ''
 return name[i:]

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

The hidden tests in test_solution.py must pass.

def ext_of(name):
    i=name.rfind('.')
    if i<=0: return ''
    return name[i:]

import unittest
from solution import ext_of
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(ext_of('a.py'), '.py')
    def test_1(self):
        self.assertEqual(ext_of('a'), '')
    def test_2(self):
        self.assertEqual(ext_of('.gitignore'), '')
    def test_3(self):
        self.assertEqual(ext_of('a.b.c'), '.c')
    def test_4(self):
        self.assertEqual(ext_of('Makefile'), '')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `ext_of`: File extension including the dot, or '' if none. Basename only. Use only the Python standard library.


Answer:
def relpath_dots(p):
 n=0
 while p.startswith('../'):
 n+=1; p=p[3:]
 return n

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

The hidden tests in test_solution.py must pass.

def relpath_dots(p):
    n=0
    while p.startswith('../'):
        n+=1; p=p[3:]
    return n

import unittest
from solution import relpath_dots
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(relpath_dots('../a'), 1)
    def test_1(self):
        self.assertEqual(relpath_dots('../../x'), 2)
    def test_2(self):
        self.assertEqual(relpath_dots('a/b'), 0)
    def test_3(self):
        self.assertEqual(relpath_dots('../../../'), 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `relpath_dots`: Count leading '../' segments in a relative path string. Use only the Python standard library.


Answer:
def semver_major(s):
 return int(s.split('.')[0])

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

The hidden tests in test_solution.py must pass.

def semver_major(s):
    return int(s.split('.')[0])

import unittest
from solution import semver_major
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(semver_major('1.2.3'), 1)
    def test_1(self):
        self.assertEqual(semver_major('0.1.0'), 0)
    def test_2(self):
        self.assertEqual(semver_major('10.0.0'), 10)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `semver_major`: Integer major version from 'X.Y.Z' (digits). Use only the Python standard library.


Answer:
def iso_week_simple(s):
 y,m,d=s.split('-')
 return int(y),int(m),int(d)

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

The hidden tests in test_solution.py must pass.

def iso_week_simple(s):
    y,m,d=s.split('-')
    return int(y),int(m),int(d)

import unittest
from solution import iso_week_simple
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(iso_week_simple('2026-08-18'), (2026, 8, 18))
    def test_1(self):
        self.assertEqual(iso_week_simple('1999-01-02'), (1999, 1, 2))

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `iso_week_simple`: Map YYYY-MM-DD to (year, month, day) ints without validation. Use only the Python standard library.

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


Answer:
def bytes_human(n):
 units=['B','KiB','MiB','GiB']
 f=float(n); i=0
 while f>=1024 and i<len(units)-1:
 f/=1024; i+=1
 if i==0: return f'{int(f)}B'
 return f'{f:.1f}{units[i]}'

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

The hidden tests in test_solution.py must pass.

def bytes_human(n):
    units=['B','KiB','MiB','GiB']
    f=float(n); i=0
    while f>=1024 and i<len(units)-1:
        f/=1024; i+=1
    if i==0: return f'{int(f)}B'
    return f'{f:.1f}{units[i]}'

import unittest
from solution import bytes_human
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(bytes_human(0), '0B')
    def test_1(self):
        self.assertEqual(bytes_human(500), '500B')
    def test_2(self):
        self.assertEqual(bytes_human(1024), '1.0KiB')
    def test_3(self):
        self.assertEqual(bytes_human(1536), '1.5KiB')
    def test_4(self):
        self.assertEqual(bytes_human(1048576), '1.0MiB')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `bytes_human`: Format n bytes as integer unit: B, KiB, MiB, GiB using 1024, one decimal if unit!=B. Use only the Python standard library.


Answer:
import re
def slug_n(s):
 toks=re.findall(r'[a-z0-9]+', s.lower())
 return '-'.join(toks)

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

The hidden tests in test_solution.py must pass.

import re
def slug_n(s):
    toks=re.findall(r'[a-z0-9]+', s.lower())
    return '-'.join(toks)

import unittest
from solution import slug_n
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(slug_n('Open Reason 1'), 'open-reason-1')
    def test_1(self):
        self.assertEqual(slug_n('Hello!!!'), 'hello')
    def test_2(self):
        self.assertEqual(slug_n('already-ok'), 'already-ok')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `slug_n`: Keep [a-z0-9]+ lowercase tokens joined by hyphen. Use only the Python standard library.


Answer:
def mask_email(s):
 if '@' not in s: return s
 local,dom=s.split('@',1)
 if not local: return s
 return local[0]+'***@'+dom

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

The hidden tests in test_solution.py must pass.

def mask_email(s):
    if '@' not in s: return s
    local,dom=s.split('@',1)
    if not local: return s
    return local[0]+'***@'+dom

import unittest
from solution import mask_email
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(mask_email('a@b.com'), 'a***@b.com')
    def test_1(self):
        self.assertEqual(mask_email('user@example.com'), 'u***@example.com')
    def test_2(self):
        self.assertEqual(mask_email('nope'), 'nope')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `mask_email`: Replace local part of an email with first char + '***' + domain; if no @ return s. Use only the Python standard library.


Answer:
def score_bowling_frame(a,b):
 if a==10: return 10
 return a+b

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

The hidden tests in test_solution.py must pass.

def score_bowling_frame(a,b):
    if a==10: return 10
    return a+b

import unittest
from solution import score_bowling_frame
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(score_bowling_frame(10, 0), 10)
    def test_1(self):
        self.assertEqual(score_bowling_frame(7, 2), 9)
    def test_2(self):
        self.assertEqual(score_bowling_frame(0, 0), 0)
    def test_3(self):
        self.assertEqual(score_bowling_frame(9, 1), 10)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `score_bowling_frame`: Score one bowling frame given two rolls 0-10; if first is 10 ignore second and return 10. Use only the Python standard library.


Answer:
def grade_pct(p):
 if p>=90: return 'A'
 if p>=80: return 'B'
 if p>=70: return 'C'
 if p>=60: return 'D'
 return 'F'

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

The hidden tests in test_solution.py must pass.

def grade_pct(p):
    if p>=90: return 'A'
    if p>=80: return 'B'
    if p>=70: return 'C'
    if p>=60: return 'D'
    return 'F'

import unittest
from solution import grade_pct
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(grade_pct(100), 'A')
    def test_1(self):
        self.assertEqual(grade_pct(90), 'A')
    def test_2(self):
        self.assertEqual(grade_pct(89), 'B')
    def test_3(self):
        self.assertEqual(grade_pct(70), 'C')
    def test_4(self):
        self.assertEqual(grade_pct(60), 'D')
    def test_5(self):
        self.assertEqual(grade_pct(59), 'F')
    def test_6(self):
        self.assertEqual(grade_pct(0), 'F')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `grade_pct`: Letter from percent: A>=90, B>=80, C>=70, D>=60 else F. Use only the Python standard library.

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok
test_5 (test_solution.Test.test_5) ... ok
test_6 (test_solution.Test.test_6) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.000s

OK

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


Answer:
def rle_decode(pairs):
 return ''.join(ch*n for ch,n in pairs)

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

The hidden tests in test_solution.py must pass.

def rle_decode(pairs):
    return ''.join(ch*n for ch,n in pairs)

import unittest
from solution import rle_decode
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(rle_decode([('a', 3), ('b', 1)]), 'aaab')
    def test_1(self):
        self.assertEqual(rle_decode([]), '')
    def test_2(self):
        self.assertEqual(rle_decode([('x', 1)]), 'x')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `rle_decode`: Decode list of (char,count) to string. Use only the Python standard library.


Answer:
def set_bits_below(n):
 return (1<<n)-1

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

The hidden tests in test_solution.py must pass.

def set_bits_below(n):
    return (1<<n)-1

import unittest
from solution import set_bits_below
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(set_bits_below(0), 0)
    def test_1(self):
        self.assertEqual(set_bits_below(1), 1)
    def test_2(self):
        self.assertEqual(set_bits_below(2), 3)
    def test_3(self):
        self.assertEqual(set_bits_below(3), 7)
    def test_4(self):
        self.assertEqual(set_bits_below(4), 15)
    def test_5(self):
        self.assertEqual(set_bits_below(5), 31)
    def test_6(self):
        self.assertEqual(set_bits_below(6), 63)
    def test_7(self):
        self.assertEqual(set_bits_below(7), 127)
    def test_8(self):
        self.assertEqual(set_bits_below(8), 255)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `set_bits_below`: Value with the lowest n bits set, n in 0..16. Use only the Python standard library.

Solution:
def set_bits_below(n):
 return (1<<n)-1

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok
test_5 (test_solution.Test.test_5) ... ok
test_6 (test_solution.Test.test_6) ... ok
test_7 (test_solution.Test.test_7) ... ok
test_8 (test_solution.Test.test_8) ... ok

----------------------------------------------------------------------
Ran 9 tests in 0.000s

OK

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


Answer:
def align_up(n,align):
 return n if n%align==0 else n+(align-n%align)

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

The hidden tests in test_solution.py must pass.

def align_up(n,align):
    return n if n%align==0 else n+(align-n%align)

import unittest
from solution import align_up
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(align_up(0, 8), 0)
    def test_1(self):
        self.assertEqual(align_up(1, 8), 8)
    def test_2(self):
        self.assertEqual(align_up(8, 8), 8)
    def test_3(self):
        self.assertEqual(align_up(15, 4), 16)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `align_up`: Smallest multiple of `align` >= n, align>0. Use only the Python standard library.


Answer:
def gray_encode(n):
 return n ^ (n>>1)

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

The hidden tests in test_solution.py must pass.

def gray_encode(n):
    return n ^ (n>>1)

import unittest
from solution import gray_encode
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(gray_encode(0), 0)
    def test_1(self):
        self.assertEqual(gray_encode(1), 1)
    def test_2(self):
        self.assertEqual(gray_encode(2), 3)
    def test_3(self):
        self.assertEqual(gray_encode(3), 2)
    def test_4(self):
        self.assertEqual(gray_encode(4), 6)
    def test_5(self):
        self.assertEqual(gray_encode(5), 7)
    def test_6(self):
        self.assertEqual(gray_encode(6), 5)
    def test_7(self):
        self.assertEqual(gray_encode(7), 4)
    def test_8(self):
        self.assertEqual(gray_encode(8), 12)
    def test_9(self):
        self.assertEqual(gray_encode(9), 13)
    def test_10(self):
        self.assertEqual(gray_encode(10), 15)
    def test_11(self):
        self.assertEqual(gray_encode(11), 14)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `gray_encode`: Binary-reflected Gray code of n: n xor (n>>1). Use only the Python standard library.

Solution:
def gray_encode(n):
 return n ^ (n>>1)

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_10 (test_solution.Test.test_10) ... ok
test_11 (test_solution.Test.test_11) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok
test_5 (test_solution.Test.test_5) ... ok
test_6 (test_solution.Test.test_6) ... ok
test_7 (test_solution.Test.test_7) ... ok
test_8 (test_solution.Test.test_8) ... ok
test_9 (test_solution.Test.test_9) ... ok

----------------------------------------------------------------------
Ran 12 tests in 0.000s

OK

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


Answer:
def is_pow2(n):
 return n>0 and (n & (n-1))==0

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

The hidden tests in test_solution.py must pass.

def is_pow2(n):
    return n>0 and (n & (n-1))==0

import unittest
from solution import is_pow2
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(is_pow2(-1), False)
    def test_1(self):
        self.assertEqual(is_pow2(0), False)
    def test_2(self):
        self.assertEqual(is_pow2(1), True)
    def test_3(self):
        self.assertEqual(is_pow2(2), True)
    def test_4(self):
        self.assertEqual(is_pow2(3), False)
    def test_5(self):
        self.assertEqual(is_pow2(4), True)
    def test_6(self):
        self.assertEqual(is_pow2(5), False)
    def test_7(self):
        self.assertEqual(is_pow2(6), False)
    def test_8(self):
        self.assertEqual(is_pow2(7), False)
    def test_9(self):
        self.assertEqual(is_pow2(8), True)
    def test_10(self):
        self.assertEqual(is_pow2(9), False)
    def test_11(self):
        self.assertEqual(is_pow2(10), False)
    def test_12(self):
        self.assertEqual(is_pow2(11), False)
    def test_13(self):
        self.assertEqual(is_pow2(12), False)
    def test_14(self):
        self.assertEqual(is_pow2(13), False)
    def test_15(self):
        self.assertEqual(is_pow2(14), False)
    def test_16(self):
        self.assertEqual(is_pow2(15), False)
    def test_17(self):
        self.assertEqual(is_pow2(16), True)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `is_pow2`: True iff n is a power of two (n>0). Use only the Python standard library.

test_0 (test_solution.Test.test_0) ... ok
test_1 (test_solution.Test.test_1) ... ok
test_10 (test_solution.Test.test_10) ... ok
test_11 (test_solution.Test.test_11) ... ok
test_12 (test_solution.Test.test_12) ... ok
test_13 (test_solution.Test.test_13) ... ok
test_14 (test_solution.Test.test_14) ... ok
test_15 (test_solution.Test.test_15) ... ok
test_16 (test_solution.Test.test_16) ... ok
test_17 (test_solution.Test.test_17) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... ok
test_4 (test_solution.Test.test_4) ... ok
test_5 (test_solution.Test.test_5) ... ok
test_6 (test_solution.Test.test_6) ... ok
test_7 (test_solution.Test.test_7) ... ok
test_8 (test_solution.Test.test_8) ... ok
test_9 (test_solution.Test.test_9) ... ok

----------------------------------------------------------------------
Ran 18 tests in 0.000s

OK

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


Answer:
def clamp_list(xs,lo,hi):
 return [lo if x<lo else hi if x>hi else x for x in xs]

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

The hidden tests in test_solution.py must pass.

def clamp_list(xs,lo,hi):
    return [lo if x<lo else hi if x>hi else x for x in xs]

import unittest
from solution import clamp_list
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(clamp_list([0, 5, 10], 1, 8), [1, 5, 8])
    def test_1(self):
        self.assertEqual(clamp_list([], 0, 1), [])
    def test_2(self):
        self.assertEqual(clamp_list([-3], 0, 1), [0])

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `clamp_list`: Clamp each value of xs into [lo,hi]. Use only the Python standard library.


Answer:
def dot(a,b):
 if len(a)!=len(b): raise ValueError('len')
 return sum(x*y for x,y in zip(a,b))

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

The hidden tests in test_solution.py must pass.

def dot(a,b):
    if len(a)!=len(b): raise ValueError('len')
    return sum(x*y for x,y in zip(a,b))

import unittest
from solution import dot
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(dot([1, 2, 3], [4, 5, 6]), 32)
    def test_1(self):
        self.assertEqual(dot([], []), 0)
    def test_2(self):
        self.assertEqual(dot([2], [3]), 6)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `dot`: Dot product of equal-length lists; ValueError otherwise. Use only the Python standard library.


Answer:
def softmax_argmax(xs):
 if not xs: return -1
 return max(range(len(xs)), key=lambda i: xs[i])

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

The hidden tests in test_solution.py must pass.

def softmax_argmax(xs):
    if not xs: return -1
    return max(range(len(xs)), key=lambda i: xs[i])

import unittest
from solution import softmax_argmax
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(softmax_argmax([0.1, 0.7, 0.2]), 1)
    def test_1(self):
        self.assertEqual(softmax_argmax([]), -1)
    def test_2(self):
        self.assertEqual(softmax_argmax([1, 1]), 0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `softmax_argmax`: Index of max in xs (first on ties); -1 if empty. (No actual softmax.) Use only the Python standard library.


Answer:
def tokenize_ws(s):
 return s.split()

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

The hidden tests in test_solution.py must pass.

def tokenize_ws(s):
    return s.split()

import unittest
from solution import tokenize_ws
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(tokenize_ws('a  b\\tc'), ['a', 'b\\tc'])
    def test_1(self):
        self.assertEqual(tokenize_ws(''), [])
    def test_2(self):
        self.assertEqual(tokenize_ws('  x'), ['x'])

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `tokenize_ws`: Split on whitespace and drop empties. Use only the Python standard library.

Solution:
def tokenize_ws(s):
 return s.split()


Answer:
def camel_from_snake(s):
 parts=[p for p in s.split('_') if p]
 if not parts: return ''
 return parts[0].lower()+''.join(p[:1].upper()+p[1:] for p in parts[1:])

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

The hidden tests in test_solution.py must pass.

def camel_from_snake(s):
    parts=[p for p in s.split('_') if p]
    if not parts: return ''
    return parts[0].lower()+''.join(p[:1].upper()+p[1:] for p in parts[1:])

import unittest
from solution import camel_from_snake
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(camel_from_snake('open_reason'), 'openReason')
    def test_1(self):
        self.assertEqual(camel_from_snake('a'), 'a')
    def test_2(self):
        self.assertEqual(camel_from_snake('already'), 'already')
    def test_3(self):
        self.assertEqual(camel_from_snake(''), '')

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `camel_from_snake`: snake_case to camelCase (first token lower). Use only the Python standard library.


Answer:
def unique_sorted(xs):
 return sorted(set(xs))

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

The hidden tests in test_solution.py must pass.

def unique_sorted(xs):
    return sorted(set(xs))

import unittest
from solution import unique_sorted
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(unique_sorted([3, 1, 2, 1]), [1, 2, 3])
    def test_1(self):
        self.assertEqual(unique_sorted([]), [])
    def test_2(self):
        self.assertEqual(unique_sorted([0, 0]), [0])

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `unique_sorted`: Sorted unique values of xs. Use only the Python standard library.


Answer:
def window_product(xs):
 if len(xs)<2: return None
 return max(xs[i]*xs[i+1] for i in range(len(xs)-1))

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

The hidden tests in test_solution.py must pass.

def window_product(xs):
    if len(xs)<2: return None
    return max(xs[i]*xs[i+1] for i in range(len(xs)-1))

import unittest
from solution import window_product
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(window_product([1, 5, 2]), 10)
    def test_1(self):
        self.assertEqual(window_product([2]), None)
    def test_2(self):
        self.assertEqual(window_product([-3, -2, 4]), 6)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `window_product`: Maximum product of any contiguous pair; None if len<2. Use only the Python standard library.


Answer:
def binsearch_exists(xs,target):
 lo,hi=0,len(xs)-1
 while lo<=hi:
 mid=(lo+hi)//2
 if xs[mid]==target: return True
 if xs[mid]<target: lo=mid+1
 else: hi=mid-1
 return False

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

The hidden tests in test_solution.py must pass.

def binsearch_exists(xs,target):
    lo,hi=0,len(xs)-1
    while lo<=hi:
        mid=(lo+hi)//2
        if xs[mid]==target: return True
        if xs[mid]<target: lo=mid+1
        else: hi=mid-1
    return False

import unittest
from solution import binsearch_exists
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(binsearch_exists([1, 3, 5, 7], 5), True)
    def test_1(self):
        self.assertEqual(binsearch_exists([1, 3, 5], 2), False)
    def test_2(self):
        self.assertEqual(binsearch_exists([], 1), False)
    def test_3(self):
        self.assertEqual(binsearch_exists([4], 4), True)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `binsearch_exists`: True iff target is in sorted xs (binary search). Use only the Python standard library.


Answer:
def binsearch_exists(xs,target):
 lo,hi=0,len(xs)-1
 while lo<=hi:
 mid=(lo+hi)//2
 if xs[mid]==target: return True
 if xs[mid]<target: lo=mid+1
 else: hi=mid-1
 return False

Do not weaken or delete tests
Keep the public API

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

test_0 (test_solution.Test.test_0) ... FAIL
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... FAIL

======================================================================
FAIL: test_0 (test_solution.Test.test_0)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-34pzawxi\test_solution.py", line 5, in test_0
    self.assertEqual(binsearch_exists([1, 3, 5, 7], 5), True)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

======================================================================
FAIL: test_3 (test_solution.Test.test_3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-34pzawxi\test_solution.py", line 11, in test_3
    self.assertEqual(binsearch_exists([4], 4), True)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

----------------------------------------------------------------------
Ran 4 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 `binsearch_exists`: True iff target is in sorted xs (binary search). Use only the Python standard library.

--- solution.py (buggy) ---
def binsearch_exists(xs,target):
 lo,hi=0,len(xs)-1
 while lo<=hi:
 mid=(lo+hi)//2
 if xs[mid]==target: return False
 if xs[mid]<target: lo=mid+1
 else: hi=mid-1
 return False

--- test_solution.py ---
import unittest
from solution import binsearch_exists
class Test(unittest.TestCase):
 def test_0(self):
 self.assertEqual(binsearch_exists([1, 3, 5, 7], 5), True)
 def test_1(self):
 self.assertEqual(binsearch_exists([1, 3, 5], 2), False)
 def test_2(self):
 self.assertEqual(binsearch_exists([], 1), False)
 def test_3(self):
 self.assertEqual(binsearch_exists([4], 4), True)

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

test_0 (test_solution.Test.test_0) ... FAIL
test_1 (test_solution.Test.test_1) ... ok
test_2 (test_solution.Test.test_2) ... ok
test_3 (test_solution.Test.test_3) ... FAIL

======================================================================
FAIL: test_0 (test_solution.Test.test_0)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-34pzawxi\test_solution.py", line 5, in test_0
 self.assertEqual(binsearch_exists([1, 3, 5, 7], 5), True)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

======================================================================
FAIL: test_3 (test_solution.Test.test_3)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-34pzawxi\test_solution.py", line 11, in test_3
 self.assertEqual(binsearch_exists([4], 4), True)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: False != True

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

FAILED (failures=2)


Answer:
def queue_ttl_ready(events,now):
 return [item for t,item in events if t<=now]

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

The hidden tests in test_solution.py must pass.

def queue_ttl_ready(events,now):
    return [item for t,item in events if t<=now]

import unittest
from solution import queue_ttl_ready
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(queue_ttl_ready([(1, 'a'), (5, 'b')], 3), ['a'])
    def test_1(self):
        self.assertEqual(queue_ttl_ready([], 0), [])
    def test_2(self):
        self.assertEqual(queue_ttl_ready([(0, 'x')], 0), ['x'])

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `queue_ttl_ready`: From list of (t,item) already sorted by t, return items with t<=now. Use only the Python standard library.


Answer:
def majority_vote(xs):
 if not xs: return None
 cand=None; v=0
 for x in xs:
 if v==0: cand=x
 v += 1 if x==cand else -1
 if xs.count(cand)>len(xs)//2: return cand
 return None

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

The hidden tests in test_solution.py must pass.

def majority_vote(xs):
    if not xs: return None
    cand=None; v=0
    for x in xs:
        if v==0: cand=x
        v += 1 if x==cand else -1
    if xs.count(cand)>len(xs)//2: return cand
    return None

import unittest
from solution import majority_vote
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(majority_vote([1, 1, 2]), 1)
    def test_1(self):
        self.assertEqual(majority_vote([1, 2, 3]), None)
    def test_2(self):
        self.assertEqual(majority_vote([]), None)
    def test_3(self):
        self.assertEqual(majority_vote([7, 7, 7, 1]), 7)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `majority_vote`: Return the unique mode if it appears > n/2 else None. Use only the Python standard library.


Answer:
def polygon_area(pts):
 n=len(pts); s=0
 for i in range(n):
 x1,y1=pts[i]; x2,y2=pts[(i+1)%n]
 s+=x1*y2-x2*y1
 return abs(s)/2

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

The hidden tests in test_solution.py must pass.

def polygon_area(pts):
    n=len(pts); s=0
    for i in range(n):
        x1,y1=pts[i]; x2,y2=pts[(i+1)%n]
        s+=x1*y2-x2*y1
    return abs(s)/2

import unittest
from solution import polygon_area
class Test(unittest.TestCase):
    def test_0(self):
        self.assertEqual(polygon_area([(0, 0), (1, 0), (0, 1)]), 0.5)
    def test_1(self):
        self.assertEqual(polygon_area([(0, 0), (2, 0), (2, 2), (0, 2)]), 4.0)

Read the specification
Implement the function or class
Satisfy the tests

Prompt: Implement `polygon_area`: Shoelace area of a simple polygon listed as (x,y) pairs, nonnegative. Use only the Python standard library.


Answer:
def rle_encode(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 count = 1
 for ch in text[1:]:
 if ch == prev:
 count += 1
 else:
 out.append(prev + str(count))
 prev = ch
 count = 1
 out.append(prev + str(count))
 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_encode(text):
    if not text:
        return ""
    out = []
    prev = text[0]
    count = 1
    for ch in text[1:]:
        if ch == prev:
            count += 1
        else:
            out.append(prev + str(count))
            prev = ch
            count = 1
    out.append(prev + str(count))
    return "".join(out)

import unittest
from solution import rle_encode

class Test(unittest.TestCase):
    def test_runs(self):
        self.assertEqual(rle_encode("aaab"), "a3b1")
    def test_empty(self):
        self.assertEqual(rle_encode(""), "")
    def test_single(self):
        self.assertEqual(rle_encode("z"), "z1")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `rle_encode(text: str) -> str`.

Replace each maximal run of the same character with that character followed by
the run length in decimal. Empty input yields empty output. Example: `aaab` ->
`a3b1`.

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

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

OK


Answer:
def rle_encode(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 count = 1
 for ch in text[1:]:
 if ch == prev:
 count += 1
 else:
 out.append(prev + str(count))
 prev = ch
 count = 1
 out.append(prev + str(count))
 return "".join(out)

Do not weaken or delete tests
Keep the public API

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

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

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

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

FAILED (failures=1)

Seeded mutation of the reference implementation.

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

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

Implement `rle_encode(text: str) -> str`.

Replace each maximal run of the same character with that character followed by
the run length in decimal. Empty input yields empty output. Example: `aaab` ->
`a3b1`.

--- solution.py (buggy) ---
def rle_encode(text):
 if not text:
 return ""
 out = []
 prev = text[0]
 count = 1
 for ch in text[1:]:
 if ch != prev:
 count += 1
 else:
 out.append(prev + str(count))
 prev = ch
 count = 1
 out.append(prev + str(count))
 return "".join(out)

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

class Test(unittest.TestCase):
 def test_runs(self):
 self.assertEqual(rle_encode("aaab"), "a3b1")
 def test_empty(self):
 self.assertEqual(rle_encode(""), "")
 def test_single(self):
 self.assertEqual(rle_encode("z"), "z1")

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

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

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

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

FAILED (failures=1)


Answer:
def max_overlap(intervals):
 events = []
 for start, end in intervals:
 events.append((start, 1))
 events.append((end, -1))
 events.sort(key=lambda item: (item[0], item[1]))
 current = 0
 best = 0
 for _, delta in events:
 current += delta
 if current > best:
 best = current
 return best

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

The hidden tests in test_solution.py must pass.

def max_overlap(intervals):
    events = []
    for start, end in intervals:
        events.append((start, 1))
        events.append((end, -1))
    events.sort(key=lambda item: (item[0], item[1]))
    current = 0
    best = 0
    for _, delta in events:
        current += delta
        if current > best:
            best = current
    return best

import unittest
from solution import max_overlap

class Test(unittest.TestCase):
    def test_overlap(self):
        self.assertEqual(max_overlap([(0, 2), (1, 3), (2, 4)]), 2)
    def test_empty(self):
        self.assertEqual(max_overlap([]), 0)
    def test_nested(self):
        self.assertEqual(max_overlap([(0, 10), (1, 2), (3, 4)]), 2)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `max_overlap(intervals) -> int`.

`intervals` is a list of half-open [start, end) pairs of ints with start < end.
Return the maximum number of intervals that cover any single integer point.
Empty input is 0.

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

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

OK


Answer:
def split_csv_row(line):
 out = []
 field = []
 i = 0
 in_quotes = False
 while i < len(line):
 ch = line[i]
 if in_quotes:
 if ch == '"':
 if i + 1 < len(line) and line[i + 1] == '"':
 field.append('"')
 i += 1
 else:
 in_quotes = False
 else:
 field.append(ch)
 else:
 if ch == '"':
 in_quotes = True
 elif ch == ",":
 out.append("".join(field))
 field = []
 else:
 field.append(ch)
 i += 1
 out.append("".join(field))
 return out

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

The hidden tests in test_solution.py must pass.

def split_csv_row(line):
    out = []
    field = []
    i = 0
    in_quotes = False
    while i < len(line):
        ch = line[i]
        if in_quotes:
            if ch == '"':
                if i + 1 < len(line) and line[i + 1] == '"':
                    field.append('"')
                    i += 1
                else:
                    in_quotes = False
            else:
                field.append(ch)
        else:
            if ch == '"':
                in_quotes = True
            elif ch == ",":
                out.append("".join(field))
                field = []
            else:
                field.append(ch)
        i += 1
    out.append("".join(field))
    return out

import unittest
from solution import split_csv_row

class Test(unittest.TestCase):
    def test_plain(self):
        self.assertEqual(split_csv_row("a,b,c"), ["a", "b", "c"])
    def test_quoted_comma(self):
        self.assertEqual(split_csv_row('a,"b,c",d'), ["a", "b,c", "d"])
    def test_escaped_quote(self):
        self.assertEqual(split_csv_row('"a""b"'), ['a"b'])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `split_csv_row(line: str) -> list[str]`.

Split a single CSV row on commas. Double-quoted fields may contain commas.
Quotes are escaped by doubling them. No newlines inside fields.

test_escaped_quote (test_solution.Test.test_escaped_quote) ... ok
test_plain (test_solution.Test.test_plain) ... ok
test_quoted_comma (test_solution.Test.test_quoted_comma) ... ok

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

OK


Answer:
def split_csv_row(line):
 out = []
 field = []
 i = 0
 in_quotes = False
 while i < len(line):
 ch = line[i]
 if in_quotes:
 if ch == '"':
 if i + 1 < len(line) and line[i + 1] == '"':
 field.append('"')
 i += 1
 else:
 in_quotes = False
 else:
 field.append(ch)
 else:
 if ch == '"':
 in_quotes = True
 elif ch == ",":
 out.append("".join(field))
 field = []
 else:
 field.append(ch)
 i += 1
 out.append("".join(field))
 return out

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_escaped_quote (test_solution.Test.test_escaped_quote) ... FAIL
test_plain (test_solution.Test.test_plain) ... ok
test_quoted_comma (test_solution.Test.test_quoted_comma) ... FAIL

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

First differing element 0:
'"""'
'a"b'

- ['"""']
+ ['a"b']

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

First differing element 1:
''
'b,c'

- ['a', '', 'cd']
?            -

+ ['a', 'b,c', 'd']
?        +++

----------------------------------------------------------------------
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 `split_csv_row(line: str) -> list[str]`.

Split a single CSV row on commas. Double-quoted fields may contain commas.
Quotes are escaped by doubling them. No newlines inside fields.

--- solution.py (buggy) ---
def split_csv_row(line):
 out = []
 field = []
 i = 0
 in_quotes = False
 while i < len(line):
 ch = line[i]
 if in_quotes:
 if ch != '"':
 if i + 1 < len(line) and line[i + 1] == '"':
 field.append('"')
 i += 1
 else:
 in_quotes = False
 else:
 field.append(ch)
 else:
 if ch == '"':
 in_quotes = True
 elif ch == ",":
 out.append("".join(field))
 field = []
 else:
 field.append(ch)
 i += 1
 out.append("".join(field))
 return out

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

class Test(unittest.TestCase):
 def test_plain(self):
 self.assertEqual(split_csv_row("a,b,c"), ["a", "b", "c"])
 def test_quoted_comma(self):
 self.assertEqual(split_csv_row('a,"b,c",d'), ["a", "b,c", "d"])
 def test_escaped_quote(self):
 self.assertEqual(split_csv_row('"a""b"'), ['a"b'])

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

test_escaped_quote (test_solution.Test.test_escaped_quote) ... FAIL
test_plain (test_solution.Test.test_plain) ... ok
test_quoted_comma (test_solution.Test.test_quoted_comma) ... FAIL

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

First differing element 0:
'"""'
'a"b'

- ['"""']
+ ['a"b']

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

First differing element 1:
''
'b,c'

- ['a', '', 'cd']
? -

+


Answer:
import heapq

def topo_order(nodes, edges):
 remaining = {node: 0 for node in nodes}
 adj = {node: [] for node in nodes}
 for src, dst in edges:
 adj[src].append(dst)
 remaining[dst] += 1
 heap = [node for node, deg in remaining.items() if deg == 0]
 heapq.heapify(heap)
 order = []
 while heap:
 node = heapq.heappop(heap)
 order.append(node)
 for nxt in adj[node]:
 remaining[nxt] -= 1
 if remaining[nxt] == 0:
 heapq.heappush(heap, nxt)
 if len(order) != len(nodes):
 return None
 return order

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

The hidden tests in test_solution.py must pass.

import heapq

def topo_order(nodes, edges):
    remaining = {node: 0 for node in nodes}
    adj = {node: [] for node in nodes}
    for src, dst in edges:
        adj[src].append(dst)
        remaining[dst] += 1
    heap = [node for node, deg in remaining.items() if deg == 0]
    heapq.heapify(heap)
    order = []
    while heap:
        node = heapq.heappop(heap)
        order.append(node)
        for nxt in adj[node]:
            remaining[nxt] -= 1
            if remaining[nxt] == 0:
                heapq.heappush(heap, nxt)
    if len(order) != len(nodes):
        return None
    return order

import unittest
from solution import topo_order

class Test(unittest.TestCase):
    def test_line(self):
        self.assertEqual(topo_order(["a", "b", "c"], [("a", "b"), ("b", "c")]), ["a", "b", "c"])
    def test_cycle(self):
        self.assertIsNone(topo_order(["a", "b"], [("a", "b"), ("b", "a")]))
    def test_lex(self):
        self.assertEqual(topo_order(["b", "a"], []), ["a", "b"])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `topo_order(nodes, edges) -> list`.

`nodes` is a list of unique hashable ids. `edges` is a list of (src, dst)
directed edges meaning src must come before dst. Return one valid topological
order. If the graph has a cycle, return None. Prefer the lexicographically
smallest node whenever several have indegree 0.

test_cycle (test_solution.Test.test_cycle) ... ok
test_lex (test_solution.Test.test_lex) ... ok
test_line (test_solution.Test.test_line) ... ok

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

OK


Answer:
import heapq

def topo_order(nodes, edges):
 remaining = {node: 0 for node in nodes}
 adj = {node: [] for node in nodes}
 for src, dst in edges:
 adj[src].append(dst)
 remaining[dst] += 1
 heap = [node for node, deg in remaining.items() if deg == 0]
 heapq.heapify(heap)
 order = []
 while heap:
 node = heapq.heappop(heap)
 order.append(node)
 for nxt in adj[node]:
 remaining[nxt] -= 1
 if remaining[nxt] == 0:
 heapq.heappush(heap, nxt)
 if len(order) != len(nodes):
 return None
 return order

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_cycle (test_solution.Test.test_cycle) ... ok
test_lex (test_solution.Test.test_lex) ... FAIL
test_line (test_solution.Test.test_line) ... FAIL

======================================================================
FAIL: test_lex (test_solution.Test.test_lex)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-evgujc39\test_solution.py", line 10, in test_lex
    self.assertEqual(topo_order(["b", "a"], []), ["a", "b"])
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: None != ['a', 'b']

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

First differing element 0:
'b'
'a'

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

----------------------------------------------------------------------
Ran 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 `topo_order(nodes, edges) -> list`.

`nodes` is a list of unique hashable ids. `edges` is a list of (src, dst)
directed edges meaning src must come before dst. Return one valid topological
order. If the graph has a cycle, return None. Prefer the lexicographically
smallest node whenever several have indegree 0.

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

def topo_order(nodes, edges):
 remaining = {node: 0 for node in nodes}
 adj = {node: [] for node in nodes}
 for src, dst in edges:
 adj[src].append(dst)
 remaining[dst] += 1
 heap = [node for node, deg in remaining.items() if deg != 0]
 heapq.heapify(heap)
 order = []
 while heap:
 node = heapq.heappop(heap)
 order.append(node)
 for nxt in adj[node]:
 remaining[nxt] -= 1
 if remaining[nxt] == 0:
 heapq.heappush(heap, nxt)
 if len(order) != len(nodes):
 return None
 return order

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

class Test(unittest.TestCase):
 def test_line(self):
 self.assertEqual(topo_order(["a", "b", "c"], [("a", "b"), ("b", "c")]), ["a", "b", "c"])
 def test_cycle(self):
 self.assertIsNone(topo_order(["a", "b"], [("a", "b"), ("b", "a")]))
 def test_lex(self):
 self.assertEqual(topo_order(["b", "a"], []), ["a", "b"])

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

test_cycle (test_solution.Test.test_cycle) ... ok
test_lex (test_solution.Test.test_lex) ... FAIL
test_line (test_solution.Test.test_line) ... FAIL

======================================================================
FAIL: test_lex (test_solution.Test.test_lex)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-evgujc39\test_solution.py", line 10, in test_lex
 self.assertEqual(topo_order(["b", "a"], []), ["a", "b"])
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: None != ['a', 'b']

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

First differing element 0:
'b'
'a'

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

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

FAILED (fa


Answer:
def popcount_bytes(data):
 return sum(bin(byte).count("1") for byte in data)

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

The hidden tests in test_solution.py must pass.

def popcount_bytes(data):
    return sum(bin(byte).count("1") for byte in data)

import unittest
from solution import popcount_bytes

class Test(unittest.TestCase):
    def test_zero(self):
        self.assertEqual(popcount_bytes(bytes([0, 0])), 0)
    def test_ff(self):
        self.assertEqual(popcount_bytes(bytes([255])), 8)
    def test_mixed(self):
        self.assertEqual(popcount_bytes(bytes([0x0F, 0xF0])), 8)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `popcount_bytes(data: bytes) -> int`.

Return the number of 1-bits in the byte string.

test_ff (test_solution.Test.test_ff) ... ok
test_mixed (test_solution.Test.test_mixed) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

OK


Answer:
def pointer_get(doc, pointer):
 if pointer == "":
 return doc
 if not pointer.startswith("/"):
 raise KeyError(pointer)
 current = doc
 for raw in pointer.split("/")[1:]:
 token = raw.replace("~1", "/").replace("~0", "~")
 if isinstance(current, list):
 current = current[int(token)]
 else:
 if token not in current:
 raise KeyError(token)
 current = current[token]
 return current

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

The hidden tests in test_solution.py must pass.

def pointer_get(doc, pointer):
    if pointer == "":
        return doc
    if not pointer.startswith("/"):
        raise KeyError(pointer)
    current = doc
    for raw in pointer.split("/")[1:]:
        token = raw.replace("~1", "/").replace("~0", "~")
        if isinstance(current, list):
            current = current[int(token)]
        else:
            if token not in current:
                raise KeyError(token)
            current = current[token]
    return current

import unittest
from solution import pointer_get

class Test(unittest.TestCase):
    def test_root(self):
        self.assertEqual(pointer_get({"a": 1}, ""), {"a": 1})
    def test_nested(self):
        self.assertEqual(pointer_get({"a": {"b": 2}}, "/a/b"), 2)
    def test_escape(self):
        self.assertEqual(pointer_get({"a/b": 3}, "/a~1b"), 3)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `pointer_get(doc, pointer: str)`.

`doc` is nested dict/list JSON-like data. `pointer` is a JSON Pointer
(RFC 6901) starting with `/` or empty for the whole document. Support `~0`
and `~1` escapes. Raise KeyError on missing keys or indexes.

test_escape (test_solution.Test.test_escape) ... ok
test_nested (test_solution.Test.test_nested) ... ok
test_root (test_solution.Test.test_root) ... ok

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

OK


Answer:
def pointer_get(doc, pointer):
 if pointer == "":
 return doc
 if not pointer.startswith("/"):
 raise KeyError(pointer)
 current = doc
 for raw in pointer.split("/")[1:]:
 token = raw.replace("~1", "/").replace("~0", "~")
 if isinstance(current, list):
 current = current[int(token)]
 else:
 if token not in current:
 raise KeyError(token)
 current = current[token]
 return current

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_escape (test_solution.Test.test_escape) ... FAIL
test_nested (test_solution.Test.test_nested) ... FAIL
test_root (test_solution.Test.test_root) ... ERROR

======================================================================
ERROR: test_root (test_solution.Test.test_root)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\test_solution.py", line 6, in test_root
    self.assertEqual(pointer_get({"a": 1}, ""), {"a": 1})
                     ~~~~~~~~~~~^^^^^^^^^^^^^^
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\solution.py", line 5, in pointer_get
    raise KeyError(pointer)
KeyError: ''

======================================================================
FAIL: test_escape (test_solution.Test.test_escape)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\test_solution.py", line 10, in test_escape
    self.assertEqual(pointer_get({"a/b": 3}, "/a~1b"), 3)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'a/b': 3} != 3

======================================================================
FAIL: test_nested (test_solution.Test.test_nested)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\test_solution.py", line 8, in test_nested
    self.assertEqual(pointer_get({"a": {"b": 2}}, "/a/b"), 2)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'a': {'b': 2}} != 2

----------------------------------------------------------------------
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 `pointer_get(doc, pointer: str)`.

`doc` is nested dict/list JSON-like data. `pointer` is a JSON Pointer
(RFC 6901) starting with `/` or empty for the whole document. Support `~0`
and `~1` escapes. Raise KeyError on missing keys or indexes.

--- solution.py (buggy) ---
def pointer_get(doc, pointer):
 if pointer != "":
 return doc
 if not pointer.startswith("/"):
 raise KeyError(pointer)
 current = doc
 for raw in pointer.split("/")[1:]:
 token = raw.replace("~1", "/").replace("~0", "~")
 if isinstance(current, list):
 current = current[int(token)]
 else:
 if token not in current:
 raise KeyError(token)
 current = current[token]
 return current

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

class Test(unittest.TestCase):
 def test_root(self):
 self.assertEqual(pointer_get({"a": 1}, ""), {"a": 1})
 def test_nested(self):
 self.assertEqual(pointer_get({"a": {"b": 2}}, "/a/b"), 2)
 def test_escape(self):
 self.assertEqual(pointer_get({"a/b": 3}, "/a~1b"), 3)

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

test_escape (test_solution.Test.test_escape) ... FAIL
test_nested (test_solution.Test.test_nested) ... FAIL
test_root (test_solution.Test.test_root) ... ERROR

======================================================================
ERROR: test_root (test_solution.Test.test_root)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\test_solution.py", line 6, in test_root
 self.assertEqual(pointer_get({"a": 1}, ""), {"a": 1})
 ~~~~~~~~~~~^^^^^^^^^^^^^^
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\solution.py", line 5, in pointer_get
 raise KeyError(pointer)
KeyError: ''

======================================================================
FAIL: test_escape (test_solution.Test.test_escape)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-27wuvki4\test_solution.py", line 10, in test_escape
 self.assertEqual(pointer_get({"a/b": 3}, "/a~1b"), 3)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'a/b': 3} != 3

======================================================================
FAIL: test_nested (test_solution.Test.test_nested)
----------------------------------------


Answer:
import datetime

def weekday_name(year, month, day):
 names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 return names[datetime.date(year, month, day).weekday()]

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

The hidden tests in test_solution.py must pass.

import datetime

def weekday_name(year, month, day):
    names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    return names[datetime.date(year, month, day).weekday()]

import unittest
from solution import weekday_name

class Test(unittest.TestCase):
    def test_known(self):
        self.assertEqual(weekday_name(2026, 8, 18), "Tuesday")
    def test_unix(self):
        self.assertEqual(weekday_name(1970, 1, 1), "Thursday")

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `weekday_name(year, month, day) -> str`.

Return the English weekday name (Monday..Sunday) for a Gregorian date in
the proleptic Gregorian calendar. Use datetime.date in the standard library.


Answer:
def group_by(items, key):
 order = []
 groups = {}
 for item in items:
 k = key(item)
 if k not in groups:
 groups[k] = []
 order.append(k)
 groups[k].append(item)
 return [(k, groups[k]) 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 group_by(items, key):
    order = []
    groups = {}
    for item in items:
        k = key(item)
        if k not in groups:
            groups[k] = []
            order.append(k)
        groups[k].append(item)
    return [(k, groups[k]) for k in order]

import unittest
from solution import group_by

class Test(unittest.TestCase):
    def test_order(self):
        rows = ["ax", "by", "az"]
        self.assertEqual(
            group_by(rows, lambda s: s[0]),
            [("a", ["ax", "az"]), ("b", ["by"])],
        )
    def test_empty(self):
        self.assertEqual(group_by([], lambda x: x), [])

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `group_by(items, key) -> list[tuple]`.

`key` is a function. Return a list of (key_value, group_list) in the order
keys first appear. Items in each group keep their original order.


Answer:
from collections import deque

def hops(graph, start, goal):
 if start == goal:
 return 0
 seen = {start}
 q = deque([(start, 0)])
 while q:
 node, dist = q.popleft()
 for nxt in graph.get(node, []):
 if nxt in seen:
 continue
 if nxt == goal:
 return dist + 1
 seen.add(nxt)
 q.append((nxt, dist + 1))
 return -1

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

The hidden tests in test_solution.py must pass.

from collections import deque

def hops(graph, start, goal):
    if start == goal:
        return 0
    seen = {start}
    q = deque([(start, 0)])
    while q:
        node, dist = q.popleft()
        for nxt in graph.get(node, []):
            if nxt in seen:
                continue
            if nxt == goal:
                return dist + 1
            seen.add(nxt)
            q.append((nxt, dist + 1))
    return -1

import unittest
from solution import hops

class Test(unittest.TestCase):
    def test_path(self):
        g = {"a": ["b"], "b": ["c"], "c": []}
        self.assertEqual(hops(g, "a", "c"), 2)
    def test_self(self):
        self.assertEqual(hops({"x": []}, "x", "x"), 0)
    def test_missing(self):
        self.assertEqual(hops({"a": ["b"], "b": []}, "a", "z"), -1)

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `hops(graph, start, goal) -> int`.

`graph` maps a node to a list of neighbors (undirected: you still only follow
listed edges). Return the fewest edges from start to goal, or -1 if unreachable.
Nodes are hashable.

test_missing (test_solution.Test.test_missing) ... ok
test_path (test_solution.Test.test_path) ... ok
test_self (test_solution.Test.test_self) ... ok

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

OK


Answer:
from collections import deque

def hops(graph, start, goal):
 if start == goal:
 return 0
 seen = {start}
 q = deque([(start, 0)])
 while q:
 node, dist = q.popleft()
 for nxt in graph.get(node, []):
 if nxt in seen:
 continue
 if nxt == goal:
 return dist + 1
 seen.add(nxt)
 q.append((nxt, dist + 1))
 return -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_missing (test_solution.Test.test_missing) ... ok
test_path (test_solution.Test.test_path) ... FAIL
test_self (test_solution.Test.test_self) ... FAIL

======================================================================
FAIL: test_path (test_solution.Test.test_path)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-60fbx36g\test_solution.py", line 7, in test_path
    self.assertEqual(hops(g, "a", "c"), 2)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 2

======================================================================
FAIL: test_self (test_solution.Test.test_self)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-60fbx36g\test_solution.py", line 9, in test_self
    self.assertEqual(hops({"x": []}, "x", "x"), 0)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 0

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

FAILED (failures=2)

Never returns when start equals goal and never checks the neighbor against goal.

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 `hops(graph, start, goal) -> int`.

`graph` maps a node to a list of neighbors (undirected: you still only follow
listed edges). Return the fewest edges from start to goal, or -1 if unreachable.
Nodes are hashable.

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

def hops(graph, start, goal):
 seen = {start}
 q = deque([(start, 0)])
 while q:
 node, dist = q.popleft()
 for nxt in graph.get(node, []):
 if nxt in seen:
 continue
 seen.add(nxt)
 q.append((nxt, dist + 1))
 return -1

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

class Test(unittest.TestCase):
 def test_path(self):
 g = {"a": ["b"], "b": ["c"], "c": []}
 self.assertEqual(hops(g, "a", "c"), 2)
 def test_self(self):
 self.assertEqual(hops({"x": []}, "x", "x"), 0)
 def test_missing(self):
 self.assertEqual(hops({"a": ["b"], "b": []}, "a", "z"), -1)

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

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

======================================================================
FAIL: test_path (test_solution.Test.test_path)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-60fbx36g\test_solution.py", line 7, in test_path
 self.assertEqual(hops(g, "a", "c"), 2)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 2

======================================================================
FAIL: test_self (test_solution.Test.test_self)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-60fbx36g\test_solution.py", line 9, in test_self
 self.assertEqual(hops({"x": []}, "x", "x"), 0)
 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -1 != 0

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

FAILED (failures=2)


Answer:
from collections import defaultdict, deque

def topo_sort(edges):
 nodes = set()
 succ = defaultdict(list)
 indeg = defaultdict(int)
 for u, v in edges:
 nodes.add(u)
 nodes.add(v)
 succ[u].append(v)
 indeg[v] += 1
 indeg.setdefault(u, indeg.get(u, 0))
 for n in nodes:
 indeg.setdefault(n, 0)
 ready = deque(sorted([n for n in nodes if indeg[n] == 0], key=str))
 out = []
 while ready:
 n = ready.popleft()
 out.append(n)
 for m in succ[n]:
 indeg[m] -= 1
 if indeg[m] == 0:
 ready.append(m)
 ready = deque(sorted(ready, key=str))
 ready = deque(sorted(ready, key=str))
 if len(out) != len(nodes):
 raise ValueError("cycle")
 return out

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

The hidden tests in test_solution.py must pass.

from collections import defaultdict, deque

def topo_sort(edges):
    nodes = set()
    succ = defaultdict(list)
    indeg = defaultdict(int)
    for u, v in edges:
        nodes.add(u)
        nodes.add(v)
        succ[u].append(v)
        indeg[v] += 1
        indeg.setdefault(u, indeg.get(u, 0))
    for n in nodes:
        indeg.setdefault(n, 0)
    ready = deque(sorted([n for n in nodes if indeg[n] == 0], key=str))
    out = []
    while ready:
        n = ready.popleft()
        out.append(n)
        for m in succ[n]:
            indeg[m] -= 1
            if indeg[m] == 0:
                ready.append(m)
                ready = deque(sorted(ready, key=str))
        ready = deque(sorted(ready, key=str))
    if len(out) != len(nodes):
        raise ValueError("cycle")
    return out

import unittest
from solution import topo_sort

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

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `topo_sort(edges) -> list`.

`edges` is a list of (u, v) pairs meaning u must come before v. Nodes may appear
only as endpoints. Return one valid topological order as a list of nodes, using
Kahn's algorithm and breaking ties by sorting ready nodes lexicographically as
strings. Raise ValueError if the graph has a cycle.

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

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

OK


Answer:
from collections import defaultdict, deque

def topo_sort(edges):
 nodes = set()
 succ = defaultdict(list)
 indeg = defaultdict(int)
 for u, v in edges:
 nodes.add(u)
 nodes.add(v)
 succ[u].append(v)
 indeg[v] += 1
 indeg.setdefault(u, indeg.get(u, 0))
 for n in nodes:
 indeg.setdefault(n, 0)
 ready = deque(sorted([n for n in nodes if indeg[n] == 0], key=str))
 out = []
 while ready:
 n = ready.popleft()
 out.append(n)
 for m in succ[n]:
 indeg[m] -= 1
 if indeg[m] == 0:
 ready.append(m)
 ready = deque(sorted(ready, key=str))
 ready = deque(sorted(ready, key=str))
 if len(out) != len(nodes):
 raise ValueError("cycle")
 return out

Do not weaken or delete tests
Keep the public API

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

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

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

Second list contains 1 additional elements.
First extra element 2:
'c'

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

======================================================================
FAIL: test_cycle (test_solution.Test.test_cycle)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-i1946nji\test_solution.py", line 10, in test_cycle
    with self.assertRaises(ValueError):
         ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: ValueError not raised

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

Second list contains 1 additional elements.
First extra element 2:
'c'

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

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

FAILED (failures=3)

Returns only left endpoints, ignores indegree and cycles.

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

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

Implement `topo_sort(edges) -> list`.

`edges` is a list of (u, v) pairs meaning u must come before v. Nodes may appear
only as endpoints. Return one valid topological order as a list of nodes, using
Kahn's algorithm and breaking ties by sorting ready nodes lexicographically as
strings. Raise ValueError if the graph has a cycle.

--- solution.py (buggy) ---
def topo_sort(edges):
 return [u for u, _ in edges]

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

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

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

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

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

Second list contains 1 additional elements.
First extra element 2:
'c'

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

======================================================================
FAIL: test_cycle (test_solution.Test.test_cycle)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\Users\matth\AppData\Local\Temp\open-reason-sandbox-i1946nji\test_solution.py", line 10, in test_cycle
 with self.assertRaises(ValueError):
 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
AssertionError: ValueError not raised

======================================================================
FAIL: test_tie (test_solution.Test.test_tie)
-------


Answer:
def ways(amount, coins):
 if amount < 0:
 return 0
 dp = [0] * (amount + 1)
 dp[0] = 1
 for c in coins:
 for x in range(c, amount + 1):
 dp[x] += dp[x - c]
 return dp[amount]

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

The hidden tests in test_solution.py must pass.

def ways(amount, coins):
    if amount < 0:
        return 0
    dp = [0] * (amount + 1)
    dp[0] = 1
    for c in coins:
        for x in range(c, amount + 1):
            dp[x] += dp[x - c]
    return dp[amount]

import unittest
from solution import ways

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

Read the specification
Implement the function or class
Satisfy the tests

Prompt:
Implement `ways(amount: int, coins: list[int]) -> int`.

Count unordered combinations of `coins` that sum to `amount`. Order of coins
does not matter. Coins may be reused. amount 0 is 1 way (empty combination).
Negative amount is 0.

test_classic (test_solution.Test.test_classic) ... ok
test_impossible (test_solution.Test.test_impossible) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

OK


Answer:
def ways(amount, coins):
 if amount < 0:
 return 0
 dp = [0] * (amount + 1)
 dp[0] = 1
 for c in coins:
 for x in range(c, amount + 1):
 dp[x] += dp[x - c]
 return dp[amount]

Do not weaken or delete tests
Keep the public API

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

test_classic (test_solution.Test.test_classic) ... FAIL
test_impossible (test_solution.Test.test_impossible) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

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

FAILED (failures=1)

Inner/outer loop swap counts permutations, not combinations.

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 `ways(amount: int, coins: list[int]) -> int`.

Count unordered combinations of `coins` that sum to `amount`. Order of coins
does not matter. Coins may be reused. amount 0 is 1 way (empty combination).
Negative amount is 0.

--- solution.py (buggy) ---
def ways(amount, coins):
 dp = [0] * (amount + 1)
 dp[0] = 1
 for x in range(1, amount + 1):
 for c in coins:
 if x >= c:
 dp[x] += dp[x - c]
 return dp[amount]

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

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

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

test_classic (test_solution.Test.test_classic) ... FAIL
test_impossible (test_solution.Test.test_impossible) ... ok
test_zero (test_solution.Test.test_zero) ... ok

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

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

FAILED (failures=1)