File size: 31,581 Bytes
92adfdd 8760602 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | {"id": "lru_ttl", "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.", "tests": "c = LRUCacheTTL(2, 10.0)\nc.put('a', 1, 0.0)\nc.put('b', 2, 1.0)\nassert c.get('a', 2.0) == 1\nc.put('c', 3, 3.0)\nassert c.get('b', 4.0) == -1\nassert c.get('a', 5.0) == 1\nassert c.get('c', 6.0) == 3\nassert c.get('a', 10.0) == -1\nc2 = LRUCacheTTL(2, 5.0)\nc2.put('x', 1, 0.0)\nc2.put('y', 2, 1.0)\nc2.put('z', 3, 5.5)\nassert c2.get('y', 5.7) == 2\nassert c2.get('x', 5.7) == -1\nassert c2.get('z', 5.7) == 3"}
{"id": "rate_limiter", "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)\nassert rl.allow('u', 0.0)\nassert rl.allow('u', 1.0)\nassert rl.allow('u', 2.0)\nassert not rl.allow('u', 3.0)\nassert rl.allow('v', 3.0)\nassert not rl.allow('u', 9.9)\nassert rl.allow('u', 10.5)\nassert not rl.allow('u', 10.6)\nassert rl.allow('u', 11.5)\nassert rl.allow('u', 12.5)\nassert not rl.allow('u', 13.0)"}
{"id": "toposort", "difficulty": "medium", "entry_point": "topo_sort", "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.", "tests": "assert topo_sort(4, [(1,0),(2,0),(3,1),(3,2)]) == [3,1,2,0]\nassert topo_sort(2, [(0,1),(1,0)]) == []\nassert topo_sort(3, []) == [0,1,2]\nassert topo_sort(6, [(5,2),(5,0),(4,0),(4,1),(2,3),(3,1)]) == [4,5,0,2,3,1]\nassert topo_sort(1, []) == [0]\nassert topo_sort(3, [(2,2)]) == []"}
{"id": "merge_intervals_ops", "difficulty": "medium", "entry_point": "apply_interval_ops", "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).", "tests": "assert apply_interval_ops([('add',1,5),('add',4,8)]) == [(1,8)]\nassert apply_interval_ops([('add',1,10),('remove',3,5)]) == [(1,3),(5,10)]\nassert apply_interval_ops([('add',1,3),('add',5,7),('add',3,5)]) == [(1,7)]\nassert apply_interval_ops([('add',0,10),('remove',0,10)]) == []\nassert apply_interval_ops([('remove',1,5),('add',2,3)]) == [(2,3)]\nassert apply_interval_ops([('add',1,2),('add',3,4),('remove',0,10),('add',5,6)]) == [(5,6)]\nassert apply_interval_ops([('add',1,100),('remove',50,60),('add',55,58)]) == [(1,50),(55,58),(60,100)]"}
{"id": "glob_match", "difficulty": "medium", "entry_point": "glob_match", "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')\nassert not glob_match('*.py', 'src/main.py')\nassert glob_match('src/**/*.py', 'src/a/b/main.py')\nassert glob_match('src/**/*.py', 'src/main.py')\nassert not glob_match('src/**/*.py', 'lib/main.py')\nassert glob_match('a?c', 'abc')\nassert not glob_match('a?c', 'ac')\nassert glob_match('**/test_*.py', 'test_x.py')\nassert glob_match('**/test_*.py', 'a/b/test_x.py')\nassert not glob_match('a/*/c', 'a/b/d/c')\nassert glob_match('a/**', 'a/b/c')\nassert not glob_match('a*b/c', 'axy/b/c')"}
{"id": "dijkstra_k", "difficulty": "medium", "entry_point": "cheapest_path_k_stops", "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.", "tests": "assert cheapest_path_k_stops(4, [(0,1,100),(1,2,100),(2,3,100),(0,3,500)], 0, 3, 1) == 500\nassert cheapest_path_k_stops(4, [(0,1,100),(1,2,100),(2,3,100),(0,3,500)], 0, 3, 2) == 300\nassert cheapest_path_k_stops(3, [(0,1,100),(1,2,100),(0,2,500)], 0, 2, 0) == 500\nassert cheapest_path_k_stops(3, [(0,1,100),(1,2,100)], 0, 2, 0) == -1\nassert cheapest_path_k_stops(2, [(0,1,100)], 0, 0, 0) == 0\nassert cheapest_path_k_stops(5, [(0,1,5),(1,2,5),(0,3,2),(3,1,2),(1,4,1),(4,2,1)], 0, 2, 2) == 7\nassert cheapest_path_k_stops(5, [(0,1,5),(1,2,5),(0,3,2),(3,1,2),(1,4,1),(4,2,1)], 0, 2, 1) == 10"}
{"id": "json_path", "difficulty": "medium", "entry_point": "json_path_get", "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.", "tests": "o = {'a': {'b': [{'c': 1}, {'c': 2}, {'c': 3}]}}\nassert json_path_get(o, 'a.b[2].c') == 3\nassert json_path_get(o, 'a.b[-1].c') == 3\nassert json_path_get(o, 'a.b[5].c', 'x') == 'x'\nassert json_path_get(o, 'a.z', 0) == 0\nassert json_path_get(o, 'a.b') == o['a']['b']\nassert json_path_get({'k': [1,2]}, 'k[0]') == 1\nassert json_path_get([1,2], 'a', -1) == -1\nassert json_path_get({'a': None}, 'a.b', 'd') == 'd'\nassert json_path_get({'a': {'b': 0}}, 'a.b', 9) == 0"}
{"id": "diff_lcs", "difficulty": "hard", "entry_point": "unified_diff_ops", "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'])\nassert ops == [('=','a'),('-','b'),('+','x'),('=','c')]\nassert unified_diff_ops([], ['a']) == [('+','a')]\nassert unified_diff_ops(['a'], []) == [('-','a')]\nassert unified_diff_ops(['a','b'], ['a','b']) == [('=','a'),('=','b')]\nops = unified_diff_ops(['a','b','c','d'], ['b','c','d','e'])\nassert ops == [('-','a'),('=','b'),('=','c'),('=','d'),('+','e')]\ndef apply(a, ops):\n out = []\n ai = 0\n for op, line in ops:\n if op == '=':\n assert a[ai] == line\n out.append(line); ai += 1\n elif op == '-':\n assert a[ai] == line\n ai += 1\n else:\n out.append(line)\n assert ai == len(a)\n return out\nimport random\nrandom.seed(7)\nfor _ in range(30):\n a = [random.choice('abcde') for _ in range(random.randint(0, 12))]\n b = [random.choice('abcde') for _ in range(random.randint(0, 12))]\n ops = unified_diff_ops(a, b)\n assert apply(a, ops) == b\n n_edit = sum(1 for op, _ in ops if op != '=')\n lcs = len(a) + len(b) - n_edit\n dp = [[0]*(len(b)+1) for _ in range(len(a)+1)]\n for i in range(len(a)):\n for j in range(len(b)):\n dp[i+1][j+1] = dp[i][j]+2 if a[i]==b[j] else max(dp[i][j+1], dp[i+1][j])\n assert lcs == dp[len(a)][len(b)]"}
{"id": "base62", "difficulty": "medium", "entry_point": "b62_encode", "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'') == ''\nassert b62_decode('') == b''\nassert b62_encode(b'\\x00\\x00\\x01') == '001'\nassert b62_decode(b62_encode(b'hello world')) == b'hello world'\nimport os, random\nrandom.seed(1)\nfor n in [1, 2, 7, 16, 33]:\n for _ in range(20):\n d = bytes(random.randrange(256) for _ in range(n))\n assert b62_decode(b62_encode(d)) == d\nassert b62_encode(b'\\x00') == '0'\nassert b62_decode('0') == b'\\x00'\nalpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\nassert b62_encode(b'\\x3d') == alpha[61]"}
{"id": "expr_eval", "difficulty": "hard", "entry_point": "eval_expr", "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\nassert eval_expr('(1+2)*3') == 9\nassert eval_expr('7//2') == 3\nassert eval_expr('-7//2') == -4\nassert eval_expr('7%3') == 1\nassert eval_expr('2*-3') == -6\nassert eval_expr('10/4') == 2.5\nassert eval_expr('1 - 2 - 3') == -4\nassert eval_expr('2 * (3 + 4) % 5') == 4\nassert abs(eval_expr('3.5 * 2 - 1/8') - 6.875) < 1e-12\nassert eval_expr('--5') == 5\ntry:\n eval_expr('1 +')\n assert False\nexcept ValueError:\n pass\ntry:\n eval_expr('(1')\n assert False\nexcept ValueError:\n pass\ntry:\n eval_expr('1 2')\n assert False\nexcept ValueError:\n pass"}
{"id": "consistent_hash", "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)\nassert ch.get('k') is None\nfor n in ['a', 'b', 'c']:\n ch.add(n)\nowner = {k: ch.get(k) for k in map(str, range(200))}\nassert set(owner.values()) == {'a', 'b', 'c'}\nch.remove('c')\nmoved = sum(1 for k, v in owner.items() if v != 'c' and ch.get(k) != v)\nassert moved == 0\nassert all(ch.get(k) in {'a', 'b'} for k in owner)\nch2 = ConsistentHash(replicas=50)\nch2.add('a'); ch2.add('b')\nassert {ch2.get(str(i)) for i in range(200)} == {'a', 'b'}\nimport hashlib\npt = int.from_bytes(hashlib.md5(b'a:0').digest()[:8], 'big')\nassert isinstance(pt, int)"}
{"id": "task_scheduler", "difficulty": "hard", "entry_point": "schedule_tasks", "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'])])\nassert r['a'] == (0, 3)\nassert r['b'] == (3, 5)\nassert r['c'] == (3, 7)\nassert r['d'] == (7, 8)\nr2 = schedule_tasks([('x', 5, [])])\nassert r2['x'] == (0, 5)\ntry:\n schedule_tasks([('a', 1, ['b']), ('b', 1, ['a'])])\n assert False\nexcept ValueError:\n pass\ntry:\n schedule_tasks([('a', 1, ['ghost'])])\n assert False\nexcept ValueError:\n pass"}
{"id": "trie_wildcard", "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()\nfor w in ['bad', 'dad', 'mad', 'badge']:\n d.add(w)\nassert not d.search('pad')\nassert d.search('bad')\nassert d.search('.ad')\nassert d.search('b..')\nassert not d.search('b.')\nassert d.search('badge')\nassert d.search('b.dge')\nassert not d.search('.....x')\nassert not d.search('')\nd.add('a')\nassert d.search('.')\nassert d.search('a')"}
{"id": "semver_resolve", "difficulty": "hard", "entry_point": "max_satisfying", "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.", "tests": "vs = ['0.2.3', '0.2.9', '0.3.0', '1.0.0', '1.2.3', '1.9.9', '2.0.0', '2.1.4']\nassert max_satisfying(vs, '^1.2.0') == '1.9.9'\nassert max_satisfying(vs, '~1.2.0') == '1.2.3'\nassert max_satisfying(vs, '^0.2.1') == '0.2.9'\nassert max_satisfying(vs, '>=1.0.0 <2.0.0') == '1.9.9'\nassert max_satisfying(vs, '>2.0.0') == '2.1.4'\nassert max_satisfying(vs, '=1.2.3') == '1.2.3'\nassert max_satisfying(vs, '>=3.0.0') is None\nassert max_satisfying(vs, '>1.2.3 <=1.9.9') == '1.9.9'\nassert max_satisfying(['1.10.0', '1.9.0', '1.2.0'], '^1.0.0') == '1.10.0'\nassert max_satisfying(vs, '^2.0.0 <2.1.0') == '2.0.0'"}
{"id": "csv_parser", "difficulty": "hard", "entry_point": "parse_csv", "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('') == []\nassert parse_csv('a,b,c') == [['a','b','c']]\nassert parse_csv('a,b\\n') == [['a','b']]\nassert parse_csv('a,\"b,c\",d') == [['a','b,c','d']]\nassert parse_csv('\"a\\nb\",c') == [['a\\nb','c']]\nassert parse_csv('\"he said \"\"hi\"\"\",x') == [['he said \"hi\"','x']]\nassert parse_csv('a,,c') == [['a','','c']]\nassert parse_csv('a\\r\\nb') == [['a'],['b']]\nassert parse_csv(',\\n,') == [['',''],['','']]\ntry:\n parse_csv('a\"b,c')\n assert False\nexcept ValueError:\n pass\ntry:\n parse_csv('\"abc')\n assert False\nexcept ValueError:\n pass"}
{"id": "regex_lite", "difficulty": "hard", "entry_point": "re_match", "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')\nassert re_match('a*b', 'b')\nassert not re_match('a+b', 'b')\nassert re_match('a+b', 'ab')\nassert re_match('a?b', 'b')\nassert re_match('a?b', 'ab')\nassert not re_match('a?b', 'aab')\nassert re_match('.*', '')\nassert re_match('a.c', 'abc')\nassert not re_match('a.c', 'ac')\nassert re_match('[abc]+', 'cab')\nassert not re_match('[abc]+', 'cad')\nassert re_match('[a-z]*[0-9]+', 'abc123')\nassert not re_match('[a-z]*[0-9]+', 'abc')\nassert re_match('ab*c', 'ac')\nassert not re_match('ab', 'abc')\nassert re_match('[a-c][x-z]?9*', 'b')"}
{"id": "bank_kernel", "difficulty": "hard", "entry_point": "process_transactions", "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([\n {'type':'deposit','id':'1','account':'a','amount':100},\n {'type':'withdraw','id':'2','account':'a','amount':30},\n {'type':'transfer','id':'3','src':'a','dst':'b','amount':50},\n {'type':'withdraw','id':'4','account':'b','amount':100},\n {'type':'deposit','id':'1','account':'a','amount':100},\n {'type':'deposit','id':'5','account':'c','amount':-5},\n])\nassert bal == {'a': 20, 'b': 50, 'c': 0}\nassert rej == ['4', '5']\nbal2, rej2 = process_transactions([\n {'type':'withdraw','id':'w','account':'x','amount':1},\n {'type':'deposit','id':'d','account':'x','amount':1},\n {'type':'withdraw','id':'w','account':'x','amount':1},\n])\nassert bal2 == {'x': 0}\nassert rej2 == ['w']\nbal3, rej3 = process_transactions([{'type':'transfer','id':'t','src':'p','dst':'p','amount':0}])\nassert rej3 == ['t']"}
{"id": "lisp_eval", "difficulty": "hard", "entry_point": "lisp_eval", "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\nassert lisp_eval('(if (< 1 2) 10 20)') == 10\nassert lisp_eval('((lambda (x) (* x x)) 7)') == 49\nassert lisp_eval('(((lambda (x) (lambda (y) (+ x y))) 3) 4)') == 7\nassert lisp_eval('(begin (define inc (lambda (n) (+ n 1))) (inc 41))') == 42\nassert lisp_eval('(begin (define fact (lambda (n) (if (< n 2) 1 (* n (fact (- n 1)))))) (fact 10))') == 3628800\nassert lisp_eval('(begin (define fib (lambda (n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))) (fib 15))') == 610\nassert lisp_eval('(begin (define make-adder (lambda (a) (lambda (b) (+ a b)))) (define add5 (make-adder 5)) (add5 (add5 1)))') == 11\nassert lisp_eval('(= 3 3)') == True\nassert lisp_eval('(- 10 4)') == 6"}
{"id": "cron_next", "difficulty": "hard", "entry_point": "cron_next", "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.", "tests": "from datetime import datetime\nassert cron_next('*/15 * * * *', datetime(2026,1,1,0,7)) == datetime(2026,1,1,0,15)\nassert cron_next('*/15 * * * *', datetime(2026,1,1,0,45)) == datetime(2026,1,1,1,0)\nassert cron_next('0 9 * * 1', datetime(2026,1,1,10,0)) == datetime(2026,1,5,9,0)\nassert cron_next('30 14 1 * *', datetime(2026,1,15,0,0)) == datetime(2026,2,1,14,30)\nassert cron_next('0 0 13 * 5', datetime(2026,1,1,0,0)) == datetime(2026,1,2,0,0)\nassert cron_next('0 0 13 * 5', datetime(2026,1,10,0,0)) == datetime(2026,1,13,0,0)\nassert cron_next('0 0 * 2 *', datetime(2026,1,20,0,0)) == datetime(2026,2,1,0,0)\nassert cron_next('5 4 * * 0', datetime(2026,1,4,4,5)) == datetime(2026,1,11,4,5)\nassert cron_next('0 12 2-10/3 * *', datetime(2026,1,3,0,0)) == datetime(2026,1,5,12,0)\nassert cron_next('59 23 31 12 *', datetime(2026,1,1,0,0)) == datetime(2026,12,31,23,59)"}
{"id": "sql_mini", "difficulty": "hard", "entry_point": "run_query", "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 = [\n {'a': 3, 'b': 'x', 'c': 10},\n {'a': 1, 'b': 'y', 'c': 30},\n {'a': 2, 'b': 'x', 'c': 20},\n {'a': 5, 'b': 'z', 'c': 20},\n]\nassert run_query(rows, \"SELECT a FROM t WHERE b = 'x' ORDER BY a ASC\") == [{'a': 2}, {'a': 3}]\nassert run_query(rows, 'SELECT * FROM t ORDER BY c DESC, a ASC LIMIT 2') == [rows[1], rows[2]]\nassert run_query(rows, \"SELECT a, c FROM t WHERE c >= 20 AND b != 'z'\") == [{'a': 1, 'c': 30}, {'a': 2, 'c': 20}]\nassert run_query(rows, \"SELECT a FROM t WHERE b = 'x' OR c = 30 ORDER BY a DESC\") == [{'a': 3}, {'a': 2}, {'a': 1}]\nassert run_query(rows, 'SELECT a FROM t LIMIT 0') == []\nassert 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'}]\nassert run_query(rows, \"SELECT a FROM t WHERE a >= 2 AND c <= 20 AND b = 'x'\") == [{'a': 3}, {'a': 2}]\nassert run_query([], 'SELECT * FROM t') == []"}
{"id": "json_schema_lite", "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'}}}}\nassert validate({'name':'lee','age':30}, s)\nassert not validate({'name':'lee'}, s)\nassert not validate({'name':'','age':30}, s)\nassert not validate({'name':'lee','age':-1}, s)\nassert not validate({'name':'lee','age':True}, s)\nassert validate({'name':'lee','age':30,'tags':['a','b'],'extra':1}, s)\nassert not validate({'name':'lee','age':30,'tags':['a',2]}, s)\nassert validate(5, {'type':'number'})\nassert validate(5.5, {'type':'number'})\nassert not validate(5.5, {'type':'integer'})\nassert not validate(True, {'type':'number'})\nassert validate(None, {'type':'null'})\nassert validate('b', {'enum':['a','b']})\nassert not validate('c', {'enum':['a','b']})\nassert not validate([1,'a'], {'type':'array','items':{'type':'integer'}})"}
{"id": "shell_tokenize", "difficulty": "hard", "entry_point": "shell_tokenize", "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']\nassert shell_tokenize(\"echo 'hello world'\") == ['echo','hello world']\nassert shell_tokenize('say \"a b\"c') == ['say','a bc']\nassert shell_tokenize('x \\\\ y') == ['x',' ','y']\nassert shell_tokenize(\"a''b\") == ['ab']\nassert shell_tokenize(\"''\") == ['']\nassert shell_tokenize('\"\"') == ['']\nassert shell_tokenize('p \"q \\\\\" r\"') == ['p','q \" r']\nassert shell_tokenize('m \"n\\\\$o\"') == ['m','n$o']\nassert shell_tokenize('k \"a\\\\bc\"') == ['k','a\\\\bc']\ntry:\n shell_tokenize(\"a 'b\")\n assert False\nexcept ValueError:\n pass\ntry:\n shell_tokenize('a \\\\')\n assert False\nexcept ValueError:\n pass"}
{"id": "tsp_heuristic", "difficulty": "optimize", "entry_point": "plan_tour", "kind": "optimize", "pass_threshold": 0.92, "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\ndef _len(pts, tour):\n return sum(math.dist(pts[tour[i]], pts[tour[(i+1)%len(tour)]]) for i in range(len(tour)))\ndef _ref(pts):\n n = len(pts)\n unv = set(range(1, n)); tour = [0]\n while unv:\n c = tour[-1]\n nxt = min(unv, key=lambda j: math.dist(pts[c], pts[j]))\n unv.remove(nxt); tour.append(nxt)\n improved = True\n while improved:\n improved = False\n for i in range(1, n - 1):\n for j in range(i + 1, n):\n a, b = tour[i-1], tour[i]\n c, d = tour[j], tour[(j+1)%n]\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:\n tour[i:j+1] = tour[i:j+1][::-1]\n improved = True\n return tour\nrandom.seed(42)\npts = [(random.uniform(0,100), random.uniform(0,100)) for _ in range(60)]\ntour = plan_tour([tuple(p) for p in pts])\nassert sorted(tour) == list(range(60)), 'not a permutation'\nref = _len(pts, _ref(pts))\ngot = _len(pts, tour)\nprint(f'LTR_SCORE: {min(1.0, ref/got):.4f}')"}
{"id": "bin_packing", "difficulty": "optimize", "entry_point": "pack", "kind": "optimize", "pass_threshold": 0.95, "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\nrandom.seed(7)\nitems = [round(random.uniform(0.05, 0.7), 3) for _ in range(120)]\ncap = 1.0\nbins = pack(list(items), cap)\nflat = sorted(x for b in bins for x in b)\nassert flat == sorted(items), 'items mismatch'\nassert all(sum(b) <= cap + 1e-9 for b in bins), 'overfull bin'\ndef _ffd(items, cap):\n bins = []\n for it in sorted(items, reverse=True):\n for b in bins:\n if sum(b) + it <= cap + 1e-9:\n b.append(it); break\n else:\n bins.append([it])\n return bins\nref = len(_ffd(items, cap))\nprint(f'LTR_SCORE: {min(1.0, ref/len(bins)):.4f}')"}
{"id": "knapsack_large", "difficulty": "optimize", "entry_point": "choose", "kind": "optimize", "pass_threshold": 0.97, "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\nrandom.seed(3)\nitems = [(random.randint(10, 400), random.randint(5, 300)) for _ in range(200)]\ncap = 5000\nidx = choose(list(items), cap)\nassert len(set(idx)) == len(idx), 'duplicate index'\nassert all(0 <= i < len(items) for i in idx)\nw = sum(items[i][1] for i in idx)\nassert w <= cap, 'over capacity'\nv = sum(items[i][0] for i in idx)\ndp = [0]*(cap+1)\nfor val, wt in items:\n for c in range(cap, wt-1, -1):\n nv = dp[c-wt] + val\n if nv > dp[c]: dp[c] = nv\nopt = dp[cap]\nprint(f'LTR_SCORE: {min(1.0, v/opt):.4f}')"}
{"id": "schedule_makespan", "difficulty": "optimize", "entry_point": "assign", "kind": "optimize", "pass_threshold": 0.92, "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\nrandom.seed(11)\njobs = [random.randint(3, 97) for _ in range(80)]\nm = 7\na = assign(list(jobs), m)\nassert len(a) == len(jobs) and all(0 <= x < m for x in a)\nloads = [0]*m\nfor j, mi in zip(jobs, a): loads[mi] += j\nmk = max(loads)\nlb = max(max(jobs), -(-sum(jobs)//m))\nprint(f'LTR_SCORE: {min(1.0, lb/mk):.4f}')"}
{"id": "compress_roundtrip", "difficulty": "optimize", "entry_point": "compress", "kind": "optimize", "pass_threshold": 0.3, "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\nbanned = {'zlib','gzip','bz2','lzma','zipfile','compression'}\nassert not (banned & set(sys.modules)), 'compression library imported'\nimport random\nrandom.seed(5)\nwords = ['the','quick','brown','fox','jumps','over','lazy','dog','routing','model','static','embedding','cheap','frontier','tokens','llm']\ncorpus = (' '.join(random.choice(words) for _ in range(20000)) + ''.join(chr(random.randint(32,126)) for _ in range(5000))).encode()\nassert not (banned & set(sys.modules)), 'compression library imported'\nblob = compress(corpus)\nassert not (banned & set(sys.modules)), 'compression library used'\nback = decompress(blob)\nassert back == corpus, 'roundtrip failed'\nsmall = b'aaaaaaaaabbbbbbbbbcccccccc' * 50\nassert decompress(compress(small)) == small\nassert decompress(compress(b'')) == b''\nimport zlib as _z\nref = len(_z.compress(corpus, 9))\nprint(f'LTR_SCORE: {min(1.0, ref/max(1,len(blob))):.4f}')"}
|