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.


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.


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


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp74ffsn17.py", line 77, in <module>
    assert b62_encode(b'\x00') == '0'
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpbe55dlhy.py", line 57, in <module>
    assert bal == {'a': 20, 'b': 50, 'c': 0}
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpjg16_xr6.py", line 141, in <module>
    assert eval_expr('7//2') == 3
           ~~~~~~~~~^^^^^^^^
  File "/nvme0n1-disk/tmp/tmpjg16_xr6.py", line 9, in eval_expr
    raise ValueError("unexpected token after expression")
ValueError: unexpected token after expression


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.


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.

 call last):
  File "/nvme0n1-disk/tmp/tmp3scanarf.py", line 130, in <module>
    assert lisp_eval('(+ 1 2 3)') == 6
           ~~~~~~~~~^^^^^^^^^^^^^
  File "/nvme0n1-disk/tmp/tmp3scanarf.py", line 127, in lisp_eval
    return eval_expr(ast, global_env)
  File "/nvme0n1-disk/tmp/tmp3scanarf.py", line 116, in eval_expr
    func = eval_expr(op, env)
  File "/nvme0n1-disk/tmp/tmp3scanarf.py", line 77, in eval_expr
    raise NameError(f"undefined variable: {expr}")
NameError: undefined variable: +


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.

me0n1-disk/tmp/tmp7xsepggx.py", line 128, in <module>
    assert cron_next('*/15 * * * *', datetime(2026,1,1,0,7)) == datetime(2026,1,1,0,15)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nvme0n1-disk/tmp/tmp7xsepggx.py", line 54, in cron_next
    start = after.replace(second=0, microsecond=0) + datetime.timedelta(minutes=1)
                                                     ^^^^^^^^^^^^^^^^^^
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp97f1bqad.py", line 104, in <module>
    assert parse_csv('a,"b,c",d') == [['a','b,c','d']]
           ~~~~~~~~~^^^^^^^^^^^^^
  File "/nvme0n1-disk/tmp/tmp97f1bqad.py", line 27, in parse_csv
    raise ValueError("Quote in unquoted field")
ValueError: Quote in unquoted field


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmptpl0r1rt.py", line 152, in <module>
    assert re_match('a*b', 'aaab')
           ~~~~~~~~^^^^^^^^^^^^^^^
AssertionError


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmps4xfjm3m.py", line 79, in <module>
    assert bal == {'a': 20, 'b': 50, 'c': 0}
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpd2259no9.py", line 172, in <module>
    assert cron_next('0 0 13 * 5', datetime(2026,1,1,0,0)) == datetime(2026,1,2,0,0)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nvme0n1-disk/tmp/tmpd2259no9.py", line 160, in cron_next
    raise ValueError("No matching time found within search limit")
ValueError: No matching time found within search limit


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp0sjb7bxa.py", line 93, in <module>
    assert len(set(idx)) == len(idx), 'duplicate index'
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: duplicate index


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp13ps75cy.py", line 373, in <module>
    back = decompress(blob)
  File "/nvme0n1-disk/tmp/tmp13ps75cy.py", line 334, in decompress
    raise ValueError("Invalid literal length 0")
ValueError: Invalid literal length 0


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.


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.


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


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpge51dhqv.py", line 133, in <module>
    assert parse_csv('') == []
           ^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpl93pymsc.py", line 84, in <module>
    assert bal == {'a': 20, 'b': 50, 'c': 0}
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp8i5eradz.py", line 142, in <module>
    assert run_query(rows, 'SELECT * FROM t ORDER BY c DESC, a ASC LIMIT 2') == [rows[1], rows[2]]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpup9k2sw9.py", line 170, in <module>
    back = decompress(blob)
  File "/nvme0n1-disk/tmp/tmpup9k2sw9.py", line 137, in decompress
    b = br.read_bits(8)
  File "/nvme0n1-disk/tmp/tmpup9k2sw9.py", line 126, in read_bits
    val = (val << 1) | self.read_bit()
                       ~~~~~~~~~~~~~^^
  File "/nvme0n1-disk/tmp/tmpup9k2sw9.py", line 119, in read_bit
    raise EOFError
EOFError


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.


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.


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


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.

  File "/nvme0n1-disk/tmp/tmpfmuxz3wq.py", line 2
    (value, now)
IndentationError: unexpected indent


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.

  File "/nvme0n1-disk/tmp/tmpfe_mmduf.py", line 1
    _segs) = 1`, `len(t_segs) = 0`). Returns True!
         ^
SyntaxError: unmatched ')'


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.

  File "/nvme0n1-disk/tmp/tmpshpzfpni.py", line 1
    re.findall(r'([^\[]+)|\[(-?\d+)\]', 'a[2')`
IndentationError: unexpected indent


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.

  File "/nvme0n1-disk/tmp/tmp86q112e1.py", line 1
    [i+1][j] <= dp[i][j+1]` (when `j < M` and we don't match)).
                                                    ^
SyntaxError: unterminated string literal (detected at line 1)


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.


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.

  File "/nvme0n1-disk/tmp/tmpq3b3kqst.py", line 1
    ```python
    ^
SyntaxError: invalid syntax


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.


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.


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.


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.


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.

  File "/nvme0n1-disk/tmp/tmp07em1sud.py", line 1
    ```python
    ^
SyntaxError: invalid syntax


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.

  File "/nvme0n1-disk/tmp/tmppwown7qz.py", line 1
    )` down to 0.
    ^
SyntaxError: unmatched ')'


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.


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.


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.

  File "/nvme0n1-disk/tmp/tmpyl5dv18p.py", line 1
    ('y', new_env)]` which are `1` and `2`.
                  ^
SyntaxError: unmatched ']'


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.

  File "/nvme0n1-disk/tmp/tmpq45jle0t.py", line 1
    if not, it's an invalid cron or an edge case we might not need to worry about, or we could set a guard. Usually we can assume a match exists.
IndentationError: unexpected indent


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.

  File "/nvme0n1-disk/tmp/tmpxxrabqbc.py", line 1
    if a column value is missing, `row.get(tok)` returns `None`, and comparing `None` to integer might raise TypeError in Python 3.
IndentationError: unexpected indent


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.

  File "/nvme0n1-disk/tmp/tmpakoftqgc.py", line 1
    ```python
    ^
SyntaxError: invalid syntax


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.

  File "/nvme0n1-disk/tmp/tmp4nc1nph8.py", line 6
    `i=0`, `c="` -> `current_word = []`, `state = DQ`, `i=1`
              ^
SyntaxError: unterminated string literal (detected at line 6)


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.

  File "/nvme0n1-disk/tmp/tmp7zh5b6ui.py", line 1
    An elegant and efficient Python implementation of the Traveling Salesman Problem (TSP) using a Multi-start Nearest Neighbor heuristic followed by an optimized 2-opt local search.
       ^^^^^^^
SyntaxError: invalid syntax


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.


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.


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.

  File "/nvme0n1-disk/tmp/tmpt18q9dsb.py", line 1
    ```python
    ^
SyntaxError: invalid syntax


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.

  File "/nvme0n1-disk/tmp/tmp1ebzm3m2.py", line 3
    The codes for this $b$ are $2b-2$ and $2b-1$.
                                ^
SyntaxError: invalid decimal literal


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.


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.


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.


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


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp7uw_l8q_.py", line 35, in <module>
    assert json_path_get(o, 'a.b[2].c') == 3
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpf2yjrwq6.py", line 62, in <module>
    assert bal == {'a': 20, 'b': 50, 'c': 0}
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmp_vy3v2l_.py", line 82, in <module>
    assert cron_next('*/15 * * * *', datetime(2026,1,1,0,7)) == datetime(2026,1,1,0,15)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nvme0n1-disk/tmp/tmp_vy3v2l_.py", line 68, in cron_next
    start = after + datetime.timedelta(minutes=1)
                    ^^^^^^^^^^^^^^^^^^
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'


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.


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.


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.


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.


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.


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.


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.


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.

Traceback (most recent call last):
  File "/nvme0n1-disk/tmp/tmpp7tbjvzc.py", line 163, in <module>
    back = decompress(blob)
  File "/nvme0n1-disk/tmp/tmpp7tbjvzc.py", line 138, in decompress
    raise ValueError("Invalid code during decompression")
ValueError: Invalid code during decompression