difficulty: medium

entry_point: LRUCacheTTL

prompt: Write a Python class LRUCacheTTL(capacity, ttl) with methods get(key, now) and put(key, value, now). now is a float timestamp passed explicitly. get returns the value or -1 if missing/expired (expired means now - insert_time >= ttl). put evicts the least-recently-used unexpired entry when over capacity, but evicts any expired entry first. get refreshes recency but not the insert time.


difficulty: medium

entry_point: SlidingWindowLimiter

prompt: Write a Python class SlidingWindowLimiter(max_requests, window_seconds) with method allow(key, now) -> bool implementing a sliding window log rate limiter per key. A request at time now is allowed iff fewer than max_requests requests for that key were allowed in the half-open interval (now - window_seconds, now]. Denied requests do not count toward the window.

tests:
rl = SlidingWindowLimiter(3, 10.0)
assert rl.allow('u', 0.0)
assert rl.allow('u', 1.0)
assert rl.allow('u', 2.0)
assert not rl.allow('u', 3.0)
assert rl.allow('v', 3.0)
assert not rl.allow('u', 9.9)
assert rl.allow('u', 10.5)
assert not rl.allow('u', 10.6)
assert rl.allow('u', 11.5)
assert rl.allow('u', 12.5)
assert not rl.allow('u', 13.0)


difficulty: medium

prompt: Write a Python function topo_sort(n, edges) that returns a topological order of nodes 0..n-1 given directed edges [(u, v), ...] meaning u before v. Among all valid orders return the lexicographically smallest. Return an empty list if the graph has a cycle.


difficulty: medium

prompt: Write a Python function apply_interval_ops(ops) where ops is a list of ('add', lo, hi) or ('remove', lo, hi) operations on half-open integer intervals [lo, hi). Apply them in order to an initially empty set and return the final covered set as a sorted list of maximal disjoint [lo, hi) pairs (tuples).


difficulty: medium

prompt: Write a Python function glob_match(pattern, text) -> bool supporting: '?' matches exactly one character, '*' matches any sequence within a path segment (never matches '/'), '**' as a complete segment matches zero or more whole segments. No regex module allowed. Character classes are not required.

tests:
assert glob_match('*.py', 'main.py')
assert not glob_match('*.py', 'src/main.py')
assert glob_match('src/**/*.py', 'src/a/b/main.py')
assert glob_match('src/**/*.py', 'src/main.py')
assert not glob_match('src/**/*.py', 'lib/main.py')
assert glob_match('a?c', 'abc')
assert not glob_match('a?c', 'ac')
assert glob_match('**/test_*.py', 'test_x.py')
assert glob_match('**/test_*.py', 'a/b/test_x.py')
assert not glob_match('a/*/c', 'a/b/d/c')
assert glob_match('a/**', 'a/b/c')
assert not glob_match('a*b/c', 'axy/b/c')


difficulty: medium

prompt: Write a Python function cheapest_path_k_stops(n, flights, src, dst, k) returning the cheapest price from src to dst with at most k intermediate stops, where flights is a list of (u, v, price). Return -1 if unreachable under the constraint.


difficulty: medium

prompt: Write a Python function json_path_get(obj, path, default=None) that evaluates a dotted path like 'a.b[2].c' against nested dicts/lists. Bracket indices may be negative. Return default on any missing key, out-of-range index, or type mismatch. Keys themselves contain no dots or brackets.


difficulty: hard

prompt: Write a Python function unified_diff_ops(a, b) taking two lists of strings and returning a minimal edit script as a list of ops: ('=', line) for lines kept, ('-', line) for deletions from a, ('+', line) for insertions from b, in order. The script must be minimal in total number of '-' and '+' ops (LCS-based) and applying it must reconstruct b from a. When multiple minimal scripts exist, emit deletions before insertions at each divergence point.

tests:
ops = unified_diff_ops(['a','b','c'], ['a','x','c'])
assert ops == [('=','a'),('-','b'),('+','x'),('=','c')]
assert unified_diff_ops([], ['a']) == [('+','a')]
assert unified_diff_ops(['a'], []) == [('-','a')]
assert unified_diff_ops(['a','b'], ['a','b']) == [('=','a'),('=','b')]
ops = unified_diff_ops(['a','b','c','d'], ['b','c','d','e'])
assert ops == [('-','a'),('=','b'),('=','c'),('=','d'),('+','e')]
def apply(a, ops):
    out = []
    ai = 0
    for op, line in ops:
        if op == '=':
            assert a[ai] == line
            out.append(line); ai += 1
        elif op == '-':
            assert a[ai] == line
            ai += 1
        else:
            out.append(line)
    assert ai == len(a)
    return out
import random
random.seed(7)
for _ in range(30):
    a = [random.choice('abcde') for _ in range(random.randint(0, 12))]
    b = [random.choice('abcde') for _ in range(random.randint(0, 12))]
    ops = unified_diff_ops(a, b)
    assert apply(a, ops) == b
    n_edit = sum(1 for op, _ in ops if op != '=')
    lcs = len(a) + len(b) - n_edit
    dp = [[0]*(len(b)+1) for _ in range(len(a)+1)]
    for i in range(len(a)):
        for j in range(len(b)):
            dp[i+1][j+1] = dp[i][j]+2 if a[i]==b[j] else max(dp[i][j+1], dp[i+1][j])
    assert lcs == dp[len(a)][len(b)]


difficulty: medium

prompt: Write Python functions b62_encode(data: bytes) -> str and b62_decode(s: str) -> bytes implementing base62 (alphabet 0-9A-Za-z) treating the bytes as a big-endian integer, with leading zero bytes preserved by prefixing one '0' character per leading zero byte. b62_encode(b'') == ''. Provide both functions.

tests:
assert b62_encode(b'') == ''
assert b62_decode('') == b''
assert b62_encode(b'\x00\x00\x01') == '001'
assert b62_decode(b62_encode(b'hello world')) == b'hello world'
import os, random
random.seed(1)
for n in [1, 2, 7, 16, 33]:
    for _ in range(20):
        d = bytes(random.randrange(256) for _ in range(n))
        assert b62_decode(b62_encode(d)) == d
assert b62_encode(b'\x00') == '0'
assert b62_decode('0') == b'\x00'
alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
assert b62_encode(b'\x3d') == alpha[61]


difficulty: hard

prompt: Write a Python function eval_expr(s) that evaluates an arithmetic expression string with +, -, *, /, //, %, unary minus, parentheses, integer and float literals, and Python precedence/associativity. Use float division for / and floor semantics matching Python for // and % on the numeric types produced. Do not use eval, exec, ast, or compile. Whitespace may appear anywhere. Raise ValueError on malformed input.

tests:
assert eval_expr('1+2*3') == 7
assert eval_expr('(1+2)*3') == 9
assert eval_expr('7//2') == 3
assert eval_expr('-7//2') == -4
assert eval_expr('7%3') == 1
assert eval_expr('2*-3') == -6
assert eval_expr('10/4') == 2.5
assert eval_expr('1 - 2 - 3') == -4
assert eval_expr('2 * (3 + 4) % 5') == 4
assert abs(eval_expr('3.5 * 2 - 1/8') - 6.875) < 1e-12
assert eval_expr('--5') == 5
try:
    eval_expr('1 +')
    assert False
except ValueError:
    pass
try:
    eval_expr('(1')
    assert False
except ValueError:
    pass
try:
    eval_expr('1 2')
    assert False
except ValueError:
    pass


difficulty: hard

entry_point: ConsistentHash

prompt: Write a Python class ConsistentHash(replicas=100) implementing a consistent hash ring using hashlib.md5 of f'{node}:{i}' (i in range(replicas)) as ring points, interpreting the first 8 bytes of the digest as a big-endian unsigned integer. Methods: add(node), remove(node), get(key) -> node for the first ring point clockwise from the md5 of the key string (same integer conversion), wrapping around. get returns None on an empty ring.

tests:
ch = ConsistentHash(replicas=50)
assert ch.get('k') is None
for n in ['a', 'b', 'c']:
    ch.add(n)
owner = {k: ch.get(k) for k in map(str, range(200))}
assert set(owner.values()) == {'a', 'b', 'c'}
ch.remove('c')
moved = sum(1 for k, v in owner.items() if v != 'c' and ch.get(k) != v)
assert moved == 0
assert all(ch.get(k) in {'a', 'b'} for k in owner)
ch2 = ConsistentHash(replicas=50)
ch2.add('a'); ch2.add('b')
assert {ch2.get(str(i)) for i in range(200)} == {'a', 'b'}
import hashlib
pt = int.from_bytes(hashlib.md5(b'a:0').digest()[:8], 'big')
assert isinstance(pt, int)


difficulty: hard

prompt: Write a Python function schedule_tasks(tasks) where tasks is a list of (name, duration, deps) with deps a list of task names. Assuming unlimited parallelism and that each task starts as soon as all deps finish, return a dict name -> (start, finish). Raise ValueError on cyclic or missing dependencies.

tests:
r = schedule_tasks([('a', 3, []), ('b', 2, ['a']), ('c', 4, ['a']), ('d', 1, ['b', 'c'])])
assert r['a'] == (0, 3)
assert r['b'] == (3, 5)
assert r['c'] == (3, 7)
assert r['d'] == (7, 8)
r2 = schedule_tasks([('x', 5, [])])
assert r2['x'] == (0, 5)
try:
    schedule_tasks([('a', 1, ['b']), ('b', 1, ['a'])])
    assert False
except ValueError:
    pass
try:
    schedule_tasks([('a', 1, ['ghost'])])
    assert False
except ValueError:
    pass


difficulty: medium

entry_point: WordDictionary

prompt: Write a Python class WordDictionary with add(word) and search(pattern) -> bool where pattern may contain '.' matching exactly one lowercase letter. Use a trie; search must not enumerate all stored words per query.

tests:
d = WordDictionary()
for w in ['bad', 'dad', 'mad', 'badge']:
    d.add(w)
assert not d.search('pad')
assert d.search('bad')
assert d.search('.ad')
assert d.search('b..')
assert not d.search('b.')
assert d.search('badge')
assert d.search('b.dge')
assert not d.search('.....x')
assert not d.search('')
d.add('a')
assert d.search('.')
assert d.search('a')


difficulty: hard

prompt: Write a Python function max_satisfying(versions, range_expr) -> str | None. versions are 'X.Y.Z' strings. range_expr is space-separated constraints that must all hold, each one of: '^X.Y.Z' (compatible: >= given, < next major; if major is 0, < next minor), '~X.Y.Z' (>= given, < next minor), '>=X.Y.Z', '<=X.Y.Z', '>X.Y.Z', '<X.Y.Z', '=X.Y.Z'. Return the highest satisfying version by numeric semver comparison, or None.


difficulty: hard

prompt: Write a Python function parse_csv(text) -> list[list[str]] implementing RFC-4180 CSV without the csv module: fields separated by commas, rows by \n or \r\n, quoted fields may contain commas, newlines, and doubled quotes ('""' -> '"'). An empty input yields []. A trailing newline does not produce an empty final row. Raise ValueError for a quote appearing inside an unquoted field or an unterminated quoted field.

tests:
assert parse_csv('') == []
assert parse_csv('a,b,c') == [['a','b','c']]
assert parse_csv('a,b\n') == [['a','b']]
assert parse_csv('a,"b,c",d') == [['a','b,c','d']]
assert parse_csv('"a\nb",c') == [['a\nb','c']]
assert parse_csv('"he said ""hi""",x') == [['he said "hi"','x']]
assert parse_csv('a,,c') == [['a','','c']]
assert parse_csv('a\r\nb') == [['a'],['b']]
assert parse_csv(',\n,') == [['',''],['','']]
try:
    parse_csv('a"b,c')
    assert False
except ValueError:
    pass
try:
    parse_csv('"abc')
    assert False
except ValueError:
    pass


difficulty: hard

prompt: Write a Python function re_match(pattern, text) -> bool for full-string matching supporting literal characters, '.', '*' (zero or more of the preceding element), '+' (one or more), '?' (zero or one), and character classes like [abc] and [a-z] (no negation). No use of the re module. Quantifiers apply to the immediately preceding literal, dot, or class.

tests:
assert re_match('a*b', 'aaab')
assert re_match('a*b', 'b')
assert not re_match('a+b', 'b')
assert re_match('a+b', 'ab')
assert re_match('a?b', 'b')
assert re_match('a?b', 'ab')
assert not re_match('a?b', 'aab')
assert re_match('.*', '')
assert re_match('a.c', 'abc')
assert not re_match('a.c', 'ac')
assert re_match('[abc]+', 'cab')
assert not re_match('[abc]+', 'cad')
assert re_match('[a-z]*[0-9]+', 'abc123')
assert not re_match('[a-z]*[0-9]+', 'abc')
assert re_match('ab*c', 'ac')
assert not re_match('ab', 'abc')
assert re_match('[a-c][x-z]?9*', 'b')


difficulty: hard

prompt: Write a Python function process_transactions(txs) simulating an account ledger. txs is a list of dicts with 'type' in {'deposit','withdraw','transfer'}, 'id' (string, globally unique per successful application), plus 'account'/'amount' for deposit/withdraw and 'src','dst','amount' for transfer. Rules: amounts must be positive ints else the tx is rejected; withdrawals/transfers fail if insufficient funds; a tx whose 'id' was already successfully applied is skipped idempotently (not an error, no effect); accounts are auto-created at balance 0. Return (balances_dict, rejected_ids_list) where rejected preserves order and includes each failing tx id once per failed attempt.

tests:
bal, rej = process_transactions([
 {'type':'deposit','id':'1','account':'a','amount':100},
 {'type':'withdraw','id':'2','account':'a','amount':30},
 {'type':'transfer','id':'3','src':'a','dst':'b','amount':50},
 {'type':'withdraw','id':'4','account':'b','amount':100},
 {'type':'deposit','id':'1','account':'a','amount':100},
 {'type':'deposit','id':'5','account':'c','amount':-5},
])
assert bal == {'a': 20, 'b': 50, 'c': 0}
assert rej == ['4', '5']
bal2, rej2 = process_transactions([
 {'type':'withdraw','id':'w','account':'x','amount':1},
 {'type':'deposit','id':'d','account':'x','amount':1},
 {'type':'withdraw','id':'w','account':'x','amount':1},
])
assert bal2 == {'x': 0}
assert rej2 == ['w']
bal3, rej3 = process_transactions([{'type':'transfer','id':'t','src':'p','dst':'p','amount':0}])
assert rej3 == ['t']


difficulty: hard

kind: exact

prompt: Write a Python function lisp_eval(src) that evaluates a mini Lisp expression string and returns the result. Support: integer literals, variables, (define name expr) at the top level of a (begin ...) form, (lambda (params...) body), (if cond then else), and builtin operators + - * < = with two or more args for + and * and exactly two for - < =. Booleans are Python True/False. Lambdas are closures with lexical scope and support recursion via define. lisp_eval receives one complete s-expression and returns its value; (begin e1 e2 ...) evaluates in order and returns the last value.

tests:
assert lisp_eval('(+ 1 2 3)') == 6
assert lisp_eval('(if (< 1 2) 10 20)') == 10
assert lisp_eval('((lambda (x) (* x x)) 7)') == 49
assert lisp_eval('(((lambda (x) (lambda (y) (+ x y))) 3) 4)') == 7
assert lisp_eval('(begin (define inc (lambda (n) (+ n 1))) (inc 41))') == 42
assert lisp_eval('(begin (define fact (lambda (n) (if (< n 2) 1 (* n (fact (- n 1)))))) (fact 10))') == 3628800
assert lisp_eval('(begin (define fib (lambda (n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))) (fib 15))') == 610
assert lisp_eval('(begin (define make-adder (lambda (a) (lambda (b) (+ a b)))) (define add5 (make-adder 5)) (add5 (add5 1)))') == 11
assert lisp_eval('(= 3 3)') == True
assert lisp_eval('(- 10 4)') == 6


difficulty: hard

kind: exact

prompt: Write a Python function cron_next(expr, after) -> datetime.datetime that returns the first time strictly after `after` matching a 5 field cron expression 'minute hour day-of-month month day-of-week'. Each field supports '*', single values, comma lists, ranges a-b, and step values like */15 or 2-10/3. day-of-week uses 0=Sunday through 6=Saturday. Standard cron semantics: if both day-of-month and day-of-week are restricted (not '*'), a date matches when EITHER matches; if only one is restricted, that one must match. Result has second and microsecond zero.


difficulty: hard

kind: exact

prompt: Write a Python function run_query(rows, sql) where rows is a list of dicts and sql is a subset of SQL: SELECT col1, col2 (or SELECT *) FROM t WHERE <cond> ORDER BY col [ASC|DESC], col2 [ASC|DESC] LIMIT n. WHERE supports comparisons =, !=, >, <, >=, <= between a column and an integer or single quoted string literal, combined with AND and OR (AND binds tighter). WHERE, ORDER BY and LIMIT are each optional. Return a list of dicts containing only the selected columns, in order. Table name is always t. Keywords are uppercase, column names lowercase.

tests:
rows = [
 {'a': 3, 'b': 'x', 'c': 10},
 {'a': 1, 'b': 'y', 'c': 30},
 {'a': 2, 'b': 'x', 'c': 20},
 {'a': 5, 'b': 'z', 'c': 20},
]
assert run_query(rows, "SELECT a FROM t WHERE b = 'x' ORDER BY a ASC") == [{'a': 2}, {'a': 3}]
assert run_query(rows, 'SELECT * FROM t ORDER BY c DESC, a ASC LIMIT 2') == [rows[1], rows[2]]
assert run_query(rows, "SELECT a, c FROM t WHERE c >= 20 AND b != 'z'") == [{'a': 1, 'c': 30}, {'a': 2, 'c': 20}]
assert run_query(rows, "SELECT a FROM t WHERE b = 'x' OR c = 30 ORDER BY a DESC") == [{'a': 3}, {'a': 2}, {'a': 1}]
assert run_query(rows, 'SELECT a FROM t LIMIT 0') == []
assert run_query(rows, "SELECT b FROM t WHERE a > 1 AND c < 25 OR b = 'y' ORDER BY a ASC") == [{'b': 'y'}, {'b': 'x'}, {'b': 'x'}, {'b': 'z'}]
assert run_query(rows, "SELECT a FROM t WHERE a >= 2 AND c <= 20 AND b = 'x'") == [{'a': 3}, {'a': 2}]
assert run_query([], 'SELECT * FROM t') == []


difficulty: medium

entry_point: validate

kind: exact

prompt: Write a Python function validate(obj, schema) -> bool implementing a JSON Schema subset: 'type' (one of 'object','array','string','integer','number','boolean','null'; booleans are NOT integers or numbers), 'properties' and 'required' for objects (extra keys allowed), 'items' as a single schema applied to every array element, 'enum' as a list of allowed values, 'minimum'/'maximum' inclusive bounds for numeric types, and 'minLength'/'maxLength' for strings. All keywords in a schema must hold. Nested schemas recurse.

tests:
s = {'type':'object','required':['name','age'],'properties':{'name':{'type':'string','minLength':1},'age':{'type':'integer','minimum':0,'maximum':150},'tags':{'type':'array','items':{'type':'string'}}}}
assert validate({'name':'lee','age':30}, s)
assert not validate({'name':'lee'}, s)
assert not validate({'name':'','age':30}, s)
assert not validate({'name':'lee','age':-1}, s)
assert not validate({'name':'lee','age':True}, s)
assert validate({'name':'lee','age':30,'tags':['a','b'],'extra':1}, s)
assert not validate({'name':'lee','age':30,'tags':['a',2]}, s)
assert validate(5, {'type':'number'})
assert validate(5.5, {'type':'number'})
assert not validate(5.5, {'type':'integer'})
assert not validate(True, {'type':'number'})
assert validate(None, {'type':'null'})
assert validate('b', {'enum':['a','b']})
assert not validate('c', {'enum':['a','b']})
assert not validate([1,'a'], {'type':'array','items':{'type':'integer'}})


difficulty: hard

kind: exact

prompt: Write a Python function shell_tokenize(line) -> list[str] implementing POSIX like shell word splitting without the shlex module: words split on unquoted spaces/tabs, single quotes preserve everything literally until the next single quote, double quotes preserve text but allow backslash to escape " \\ and $ (backslash before other chars stays literal inside double quotes), unquoted backslash escapes the next character. Adjacent quoted and unquoted parts concatenate into one word. Empty quoted strings produce empty words. Raise ValueError on unterminated quotes or a trailing lone backslash.

tests:
assert shell_tokenize('a b  c') == ['a','b','c']
assert shell_tokenize("echo 'hello world'") == ['echo','hello world']
assert shell_tokenize('say "a b"c') == ['say','a bc']
assert shell_tokenize('x \\  y') == ['x',' ','y']
assert shell_tokenize("a''b") == ['ab']
assert shell_tokenize("''") == ['']
assert shell_tokenize('""') == ['']
assert shell_tokenize('p "q \\" r"') == ['p','q " r']
assert shell_tokenize('m "n\\$o"') == ['m','n$o']
assert shell_tokenize('k "a\\bc"') == ['k','a\\bc']
try:
    shell_tokenize("a 'b")
    assert False
except ValueError:
    pass
try:
    shell_tokenize('a \\')
    assert False
except ValueError:
    pass


difficulty: optimize

kind: optimize

prompt: Write a Python function plan_tour(points) -> list[int] for the euclidean travelling salesman problem: points is a list of (x, y) floats, return a permutation of all indices as the visiting order of a closed tour (returns to start). Minimize total tour length. There is no optimal requirement, shorter is better; a strong heuristic like nearest neighbour plus 2-opt within a couple of seconds is expected. Deterministic output required.

tests:
import math, random
def _len(pts, tour):
    return sum(math.dist(pts[tour[i]], pts[tour[(i+1)%len(tour)]]) for i in range(len(tour)))
def _ref(pts):
    n = len(pts)
    unv = set(range(1, n)); tour = [0]
    while unv:
        c = tour[-1]
        nxt = min(unv, key=lambda j: math.dist(pts[c], pts[j]))
        unv.remove(nxt); tour.append(nxt)
    improved = True
    while improved:
        improved = False
        for i in range(1, n - 1):
            for j in range(i + 1, n):
                a, b = tour[i-1], tour[i]
                c, d = tour[j], tour[(j+1)%n]
                if math.dist(pts[a],pts[c]) + math.dist(pts[b],pts[d]) < math.dist(pts[a],pts[b]) + math.dist(pts[c],pts[d]) - 1e-12:
                    tour[i:j+1] = tour[i:j+1][::-1]
                    improved = True
    return tour
random.seed(42)
pts = [(random.uniform(0,100), random.uniform(0,100)) for _ in range(60)]
tour = plan_tour([tuple(p) for p in pts])
assert sorted(tour) == list(range(60)), 'not a permutation'
ref = _len(pts, _ref(pts))
got = _len(pts, tour)
print(f'LTR_SCORE: {min(1.0, ref/got):.4f}')


difficulty: optimize

entry_point: pack

kind: optimize

prompt: Write a Python function pack(items, capacity) -> list[list[float]] for one dimensional bin packing: items is a list of positive floats each <= capacity. Return bins as lists of item values whose per bin sum is <= capacity and which together use every item exactly once (multiset equality). Fewer bins is better; first fit decreasing or better is expected. Deterministic output required.

tests:
import random
random.seed(7)
items = [round(random.uniform(0.05, 0.7), 3) for _ in range(120)]
cap = 1.0
bins = pack(list(items), cap)
flat = sorted(x for b in bins for x in b)
assert flat == sorted(items), 'items mismatch'
assert all(sum(b) <= cap + 1e-9 for b in bins), 'overfull bin'
def _ffd(items, cap):
    bins = []
    for it in sorted(items, reverse=True):
        for b in bins:
            if sum(b) + it <= cap + 1e-9:
                b.append(it); break
        else:
            bins.append([it])
    return bins
ref = len(_ffd(items, cap))
print(f'LTR_SCORE: {min(1.0, ref/len(bins)):.4f}')


difficulty: optimize

entry_point: choose

kind: optimize

prompt: Write a Python function choose(items, capacity) -> list[int] for the 0/1 knapsack problem: items is a list of (value, weight) positive int pairs, return indices of a subset with total weight <= capacity maximizing total value. Instances have up to 200 items and capacity up to 5000, so exact DP is feasible but any high quality method is accepted. Deterministic output required.

tests:
import random
random.seed(3)
items = [(random.randint(10, 400), random.randint(5, 300)) for _ in range(200)]
cap = 5000
idx = choose(list(items), cap)
assert len(set(idx)) == len(idx), 'duplicate index'
assert all(0 <= i < len(items) for i in idx)
w = sum(items[i][1] for i in idx)
assert w <= cap, 'over capacity'
v = sum(items[i][0] for i in idx)
dp = [0]*(cap+1)
for val, wt in items:
    for c in range(cap, wt-1, -1):
        nv = dp[c-wt] + val
        if nv > dp[c]: dp[c] = nv
opt = dp[cap]
print(f'LTR_SCORE: {min(1.0, v/opt):.4f}')


difficulty: optimize

entry_point: assign

kind: optimize

prompt: Write a Python function assign(jobs, m) -> list[int] scheduling jobs (list of positive int durations) onto m identical machines to minimize makespan (max machine load). Return a machine index in range(m) for each job. Lower makespan is better; LPT or better is expected, local search welcome. Deterministic output required.

tests:
import random
random.seed(11)
jobs = [random.randint(3, 97) for _ in range(80)]
m = 7
a = assign(list(jobs), m)
assert len(a) == len(jobs) and all(0 <= x < m for x in a)
loads = [0]*m
for j, mi in zip(jobs, a): loads[mi] += j
mk = max(loads)
lb = max(max(jobs), -(-sum(jobs)//m))
print(f'LTR_SCORE: {min(1.0, lb/mk):.4f}')


difficulty: optimize

entry_point: compress

kind: optimize

prompt: Write Python functions compress(data: bytes) -> bytes and decompress(blob: bytes) -> bytes implementing your own lossless compressor. You may NOT use zlib, gzip, bz2, lzma, zipfile or any compression library; write the algorithm yourself (LZ77/LZSS with a window, plus optional Huffman or byte pair encoding, is a good target). decompress(compress(data)) must equal data exactly for arbitrary bytes. Smaller output is better; you are scored on compressed size relative to zlib level 9 on a mixed text corpus, and matching zlib is not required. Both functions must be deterministic and run within a few seconds on 200KB.

tests:
import sys
banned = {'zlib','gzip','bz2','lzma','zipfile','compression'}
assert not (banned & set(sys.modules)), 'compression library imported'
import random
random.seed(5)
words = ['the','quick','brown','fox','jumps','over','lazy','dog','routing','model','static','embedding','cheap','frontier','tokens','llm']
corpus = (' '.join(random.choice(words) for _ in range(20000)) + ''.join(chr(random.randint(32,126)) for _ in range(5000))).encode()
assert not (banned & set(sys.modules)), 'compression library imported'
blob = compress(corpus)
assert not (banned & set(sys.modules)), 'compression library used'
back = decompress(blob)
assert back == corpus, 'roundtrip failed'
small = b'aaaaaaaaabbbbbbbbbcccccccc' * 50
assert decompress(compress(small)) == small
assert decompress(compress(b'')) == b''
import zlib as _z
ref = len(_z.compress(corpus, 9))
print(f'LTR_SCORE: {min(1.0, ref/max(1,len(blob))):.4f}')