id stringclasses 50
values | testsource stringclasses 6
values | language stringclasses 6
values | prefix stringlengths 16 3.39k | golden_completion stringlengths 23 3.14k | suffix stringlengths 0 2.68k | assertions stringlengths 0 2.72k | category stringclasses 6
values |
|---|---|---|---|---|---|---|---|
1 | devbench-code2NL-NL2code | python | import csv
from io import StringIO
def write_strict_csv(rows, fieldnames):
out = StringIO(newline='')
writer = csv.DictWriter(
out,
fieldnames=fieldnames,
extrasaction='raise',
lineterminator='\n',
)
writer.writeheader()
writer.writerows(rows)
return out.getvalue... | return (
"write_strict_csv serializes dictionaries with csv.DictWriter using the supplied "
"fieldnames order, writes the header row with writeheader(), and returns the "
"StringIO CSV text. It sets extrasaction='raise', so any row containing a key "
"outside fieldnames raises ValueE... |
csv_text = write_strict_csv([{'name': 'Ada', 'score': 9}, {'name': 'Lin', 'score': 8}], ['name', 'score'])
assert csv_text == 'name,score\nAda,9\nLin,8\n'
try:
write_strict_csv([{'name': 'Ada', 'score': 9, 'extra': True}], ['name', 'score'])
assert False, 'extra keys should raise'
except ValueError:
pass
s... | doc = describe_write_strict_csv()
assert isinstance(doc, str), 'describe_write_strict_csv must return a string'
low = doc.lower()
assert 'csv.dictwriter' in low or 'dictwriter' in low, 'Must mention csv.DictWriter'
assert 'fieldnames' in low, 'Must mention fieldnames ordering'
assert 'writeheader' in low or 'header row... | code2NL_NL2code |
2 | devbench-code2NL-NL2code | python | from urllib.parse import parse_qsl
def read_query_pairs(query):
if query.startswith('?'):
query = query[1:]
return parse_qsl(query, keep_blank_values=True, strict_parsing=True)
def describe_read_query_pairs():
| return (
"read_query_pairs strips one leading '?' and calls urllib.parse.parse_qsl with "
"keep_blank_values=True and strict_parsing=True. It returns an ordered list "
"of (key, value) pairs rather than a dict, so duplicate keys are preserved; "
"blank values remain empty strings, pl... |
pairs = read_query_pairs('?a=1&empty=&a=2&name=Ada+Lovelace')
assert pairs == [('a', '1'), ('empty', ''), ('a', '2'), ('name', 'Ada Lovelace')]
try:
read_query_pairs('ok=1&broken')
assert False, 'strict parsing should reject fields without ='
except ValueError:
pass
summary = describe_read_query_pairs()
as... | doc = describe_read_query_pairs()
assert isinstance(doc, str), 'describe_read_query_pairs must return a string'
low = doc.lower()
assert 'parse_qsl' in low, 'Must mention parse_qsl'
assert 'keep_blank_values' in low or 'blank value' in low, 'Must mention blank-value preservation'
assert 'strict_parsing' in low or 'stri... | code2NL_NL2code |
3 | devbench-code2NL-NL2code | python | def safe_divide(a, b):
| """Divide a by b, returning None instead of raising
ZeroDivisionError when b is zero. Returns a float result
for valid divisions.
"""
| if b == 0:
return None
return a / b
assert safe_divide(10, 2) == 5.0
assert safe_divide(0, 5) == 0.0
assert safe_divide(7, 0) is None
| assert safe_divide(1, 3) == 1/3
assert safe_divide(-6, 2) == -3.0
assert safe_divide(0, 0) is None
assert safe_divide(100, 0) is None
assert type(safe_divide(4, 2)) is float
| code2NL_NL2code |
4 | devbench-code2NL-NL2code | python | _call_count = 0
def tracked_add(a, b):
| """Add two numbers and return the result.
Side effect: increments the module-level _call_count variable
on every call. This can be used to track how many times the
function has been invoked.
"""
| global _call_count
_call_count += 1
return a + b
_call_count = 0
assert tracked_add(2, 3) == 5
assert _call_count == 1
tracked_add(0, 0)
assert _call_count == 2
| _call_count = 0
for i in range(10):
tracked_add(i, i)
assert _call_count == 10
tracked_add(1, 1)
assert _call_count == 11
| code2NL_NL2code |
5 | devbench-code2NL-NL2code | python | def find_index(lst, value):
| """Return the index of the first occurrence of value in lst.
If value appears exactly once, returns an int. If value appears
multiple times, returns a list of all indices. If value is not
found, returns -1.
"""
| indices = [i for i, x in enumerate(lst) if x == value]
if len(indices) == 0:
return -1
elif len(indices) == 1:
return indices[0]
else:
return indices
assert find_index([10, 20, 30], 20) == 1
assert find_index([1, 2, 1, 3, 1], 1) == [0, 2, 4]
assert find_index([1, 2, 3], 99) == -... | assert find_index([], 1) == -1
assert find_index([5], 5) == 0
assert type(find_index([5], 5)) is int
assert find_index([5, 5], 5) == [0, 1]
assert type(find_index([5, 5], 5)) is list
assert find_index([1, 2, 3, 2], 2) == [1, 3]
| code2NL_NL2code |
6 | devbench-code2NL-NL2code | python | import bisect
import operator
def insert_by_score(records, score, payload):
index = bisect.bisect_left(records, score, key=operator.itemgetter('score'))
records.insert(index, {'score': score, 'payload': payload})
return index
def describe_insert_by_score():
| return (
"insert_by_score uses bisect.bisect_left with key=operator.itemgetter('score') "
"to search a list of record dictionaries by their score field. The probe value "
"is the raw score, not a record, because bisect's key is applied to list items "
"rather than to x. Equal scores ... |
rows = [{'score': 10, 'payload': 'a'}, {'score': 20, 'payload': 'b'}]
pos = insert_by_score(rows, 15, 'mid')
assert pos == 1
assert rows == [{'score': 10, 'payload': 'a'}, {'score': 15, 'payload': 'mid'}, {'score': 20, 'payload': 'b'}]
pos2 = insert_by_score(rows, 15, 'tie')
assert pos2 == 1
assert [r['payload'] for r... | doc = describe_insert_by_score()
assert isinstance(doc, str), 'describe_insert_by_score must return a string'
low = doc.lower()
assert 'bisect_left' in low or 'bisect.bisect_left' in low, 'Must mention bisect_left'
assert 'operator.itemgetter' in low or 'itemgetter' in low, 'Must mention operator.itemgetter key'
assert... | code2NL_NL2code |
7 | devbench-code2NL-NL2code | python | def parse_int_graceful(s, default=0):
| """Parse a string as an integer, stripping leading/trailing whitespace.
Returns the parsed integer on success. If parsing fails for any
reason (non-numeric string, None input, etc.), returns the default
value instead of raising an exception. The default is 0 if not
specified.
"""
| try:
return int(str(s).strip())
except (ValueError, TypeError):
return default
assert parse_int_graceful("42") == 42
assert parse_int_graceful(" -7 ") == -7
assert parse_int_graceful("abc") == 0
assert parse_int_graceful(None) == 0
assert parse_int_graceful("xyz", default=-1) == -1
| assert parse_int_graceful("") == 0
assert parse_int_graceful(" ") == 0
assert parse_int_graceful("3.14") == 0
assert parse_int_graceful("123abc") == 0
assert parse_int_graceful(None, default=99) == 99
assert parse_int_graceful("100") == 100
| code2NL_NL2code |
8 | devbench-code2NL-NL2code | python | from datetime import datetime, timezone
def parse_log_timestamp(text):
parsed = datetime.strptime(text, '%Y-%m-%dT%H:%M:%S%z')
return parsed.astimezone(timezone.utc)
def describe_parse_log_timestamp():
| return (
"parse_log_timestamp parses text with datetime.strptime using the exact "
"'%Y-%m-%dT%H:%M:%S%z' format. The %z directive requires and interprets "
"a numeric UTC offset, producing an aware datetime, then astimezone(timezone.utc) "
"normalizes the result to UTC. Invalid text... |
from datetime import timedelta
assert parse_log_timestamp('2026-04-30T10:15:00+0200') == datetime(2026, 4, 30, 8, 15, tzinfo=timezone.utc)
assert parse_log_timestamp('2026-04-30T10:15:00-0730') == datetime(2026, 4, 30, 17, 45, tzinfo=timezone.utc)
try:
parse_log_timestamp('2026-04-30T10:15:00')
assert False, '... | doc = describe_parse_log_timestamp()
assert isinstance(doc, str), 'describe_parse_log_timestamp must return a string'
low = doc.lower()
assert 'datetime.strptime' in low or 'strptime' in low, 'Must mention datetime.strptime'
assert '%z' in doc, 'Must mention the %z offset directive'
assert 'offset' in low, 'Must mentio... | code2NL_NL2code |
9 | devbench-code2NL-NL2code | python | import hashlib
def sha256_stream_hex(stream, chunk_size=8192):
start = stream.tell()
digest = hashlib.sha256()
try:
for block in iter(lambda: stream.read(chunk_size), b''):
digest.update(block)
return digest.hexdigest()
finally:
stream.seek(start)
def describe_sha25... | return (
"sha256_stream_hex hashes a seekable binary stream without consuming its "
"position: it saves stream.tell(), reads bytes in chunk_size blocks until b'', "
"feeds each block to hashlib.sha256().update(), returns the digest.hexdigest() "
"64-character lowercase hexadecimal st... |
from io import BytesIO
stream = BytesIO(b'abc')
assert sha256_stream_hex(stream, chunk_size=2) == hashlib.sha256(b'abc').hexdigest()
assert stream.tell() == 0
stream.seek(1)
assert sha256_stream_hex(stream, chunk_size=1) == hashlib.sha256(b'bc').hexdigest()
assert stream.tell() == 1
summary = describe_sha256_stream_he... | doc = describe_sha256_stream_hex()
assert isinstance(doc, str), 'describe_sha256_stream_hex must return a string'
low = doc.lower()
assert 'hashlib.sha256' in low or 'sha256()' in low, 'Must mention hashlib.sha256()'
assert 'update' in low, 'Must mention digest.update()'
assert 'chunk' in low or 'block' in low, 'Must m... | code2NL_NL2code |
10 | devbench-code2NL-NL2code | python | import json
def load_json_pairs(text):
return json.loads(text, object_pairs_hook=list)
def describe_load_json_pairs():
| return (
"load_json_pairs calls json.loads with object_pairs_hook=list, so each JSON "
"object is decoded as an ordered list of (key, value) pairs instead of a dict. "
"That preserves duplicate keys and source order, applies to nested objects too, "
"leaves arrays as normal lists, an... |
parsed = load_json_pairs('{"a": 1, "a": 2, "b": {"x": 3}}')
assert parsed == [('a', 1), ('a', 2), ('b', [('x', 3)])]
assert load_json_pairs('[{"x": 1}, {"x": 2}]') == [[('x', 1)], [('x', 2)]]
try:
load_json_pairs('{bad json}')
assert False, 'invalid JSON should raise'
except json.JSONDecodeError:
pass
summ... | doc = describe_load_json_pairs()
assert isinstance(doc, str), 'describe_load_json_pairs must return a string'
low = doc.lower()
assert 'json.loads' in low or 'loads' in low, 'Must mention json.loads'
assert 'object_pairs_hook' in low, 'Must mention object_pairs_hook'
assert 'list' in low and ('pair' in low or 'tuple' i... | code2NL_NL2code |
11 | devbench-code2NL-NL2code | python | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP, localcontext
def quantize_money(value):
with localcontext() as ctx:
ctx.traps[InvalidOperation] = True
amount = Decimal(str(value))
return amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
def describe_quantize_money():
| return (
"quantize_money converts the input through Decimal(str(value)) inside a "
"localcontext whose InvalidOperation trap is enabled, then returns a Decimal "
"quantized to Decimal('0.01') with ROUND_HALF_UP. It rounds to exactly two "
"decimal places, uses half-up rather than bin... |
assert quantize_money('1.005') == Decimal('1.01')
assert quantize_money('1.004') == Decimal('1.00')
assert quantize_money(2) == Decimal('2.00')
try:
quantize_money('not-money')
assert False, 'invalid decimal should raise'
except InvalidOperation:
pass
summary = describe_quantize_money()
assert isinstance(s... | doc = describe_quantize_money()
assert isinstance(doc, str), 'describe_quantize_money must return a string'
low = doc.lower()
assert 'decimal' in low, 'Must mention Decimal'
assert 'quantize' in low, 'Must mention quantize'
assert '0.01' in doc or 'two decimal' in low or '2 decimal' in low, 'Must mention two-place quan... | code2NL_NL2code |
12 | devbench-code2NL-NL2code | python | from dataclasses import dataclass, replace, asdict
@dataclass(frozen=True)
class Job:
name: str
retries: int = 0
tags: tuple = ()
def retry_job(job, reason):
updated = replace(job, retries=job.retries + 1, tags=job.tags + (reason,))
return updated, asdict(updated)
def describe_retry_job():
| return (
"retry_job works with a frozen dataclass Job by using dataclasses.replace "
"to create a new instance with retries incremented and tags extended by tuple "
"concatenation. The original Job is unchanged, the returned first value is the "
"new Job instance, and the second valu... |
job = Job('sync')
updated, snapshot = retry_job(job, 'timeout')
assert job == Job('sync', 0, ())
assert updated == Job('sync', 1, ('timeout',))
assert snapshot == {'name': 'sync', 'retries': 1, 'tags': ('timeout',)}
updated2, snapshot2 = retry_job(updated, 'again')
assert updated2.tags == ('timeout', 'again')
assert s... | doc = describe_retry_job()
assert isinstance(doc, str), 'describe_retry_job must return a string'
low = doc.lower()
assert 'dataclass' in low, 'Must mention dataclass'
assert 'frozen' in low or 'immutable' in low, 'Must mention frozen/immutable Job behavior'
assert 'replace' in low, 'Must mention dataclasses.replace'
a... | code2NL_NL2code |
13 | devbench-code2NL-NL2code | python | import heapq
def newest_high_priority(events, limit):
return heapq.nlargest(limit, events, key=lambda event: (event['priority'], event['created_at']))
def describe_newest_high_priority():
| return (
"newest_high_priority returns heapq.nlargest(limit, events, key=...) using "
"a tuple key of (priority, created_at). Higher priority ranks first, and "
"created_at breaks ties by choosing the newest/largest timestamp first. The "
"function returns the selected event dictiona... |
events = [
{'id': 'old-high', 'priority': 5, 'created_at': 10},
{'id': 'low-new', 'priority': 1, 'created_at': 99},
{'id': 'new-high', 'priority': 5, 'created_at': 20},
{'id': 'mid', 'priority': 3, 'created_at': 50},
]
original = list(events)
selected = newest_high_priority(events, 2)
assert [e['id'] f... | doc = describe_newest_high_priority()
assert isinstance(doc, str), 'describe_newest_high_priority must return a string'
low = doc.lower()
assert 'heapq.nlargest' in low or 'nlargest' in low, 'Must mention heapq.nlargest'
assert 'limit' in low, 'Must mention limit parameter'
assert 'tuple' in low or '(priority' in low, ... | code2NL_NL2code |
14 | devbench-code2NL-NL2code | python | from pathlib import PurePosixPath
def posix_path_snapshot(path):
p = PurePosixPath(path)
return {
'text': p.as_posix(),
'parts': p.parts,
'name': p.name,
'suffixes': p.suffixes,
'parent': p.parent.as_posix(),
}
def describe_posix_path_snapshot():
| return (
"posix_path_snapshot uses pathlib.PurePosixPath, so it performs lexical "
"POSIX path parsing without touching the filesystem and without resolving '..'. "
"It returns p.as_posix() text, the p.parts tuple, the final p.name, the p.suffixes "
"list for all extensions, and the ... |
snap = posix_path_snapshot('/var/log/../app/archive.tar.gz')
assert snap['text'] == '/var/log/../app/archive.tar.gz'
assert snap['parts'] == ('/', 'var', 'log', '..', 'app', 'archive.tar.gz')
assert snap['name'] == 'archive.tar.gz'
assert snap['suffixes'] == ['.tar', '.gz']
assert snap['parent'] == '/var/log/../app'
s... | doc = describe_posix_path_snapshot()
assert isinstance(doc, str), 'describe_posix_path_snapshot must return a string'
low = doc.lower()
assert 'pathlib' in low or 'pureposixpath' in low, 'Must mention pathlib.PurePosixPath'
assert 'lexical' in low or 'without touching' in low or 'filesystem' in low, 'Must mention lexic... | code2NL_NL2code |
15 | devbench-code2NL-NL2code | python | def run_length_encode(s):
"""Encode a string using run-length encoding.
Consecutive identical characters are replaced by the character
followed by its count. Single characters (count=1) are still
followed by '1'. Returns the encoded string.
Example: "aaabbc" -> "a3b2c1"
Empty string returns em... | if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + str(count))
count = 1
result.append(s[-1] + str(count))
return "".join(result)
|
assert run_length_encode("aaabbc") == "a3b2c1"
assert run_length_encode("") == ""
assert run_length_encode("a") == "a1"
assert run_length_encode("aaa") == "a3"
| assert run_length_encode("abcdef") == "a1b1c1d1e1f1"
assert run_length_encode("aabbcc") == "a2b2c2"
assert run_length_encode("aaaaaaaaaa") == "a10"
assert run_length_encode("ab") == "a1b1"
assert run_length_encode("aab") == "a2b1"
| code2NL_NL2code |
16 | devbench-code2NL-NL2code | python | def stable_partition_in_place(items, keep):
| """Stably partition items in place according to keep.
Items for which keep(item) is true are moved to the front, followed
by the remaining items, while preserving relative order within both
groups. The predicate is called exactly once for each original item.
The same list object is mutated, and the... | kept = []
rejected = []
for item in items:
if keep(item):
kept.append(item)
else:
rejected.append(item)
items[:] = kept + rejected
return len(kept)
data = [3, 2, 4, 1, 6]
idx = stable_partition_in_place(data, lambda x: x % 2 == 0)
assert idx == 3
assert data ... | docstring = stable_partition_in_place.__doc__
assert docstring is not None, 'Docstring is missing'
low = docstring.lower()
assert 'in place' in low or 'in-place' in low or 'mutat' in low, 'Must mention in-place mutation'
assert 'stable' in low or 'relative order' in low or 'preserv' in low, 'Must mention stable/order-p... | code2NL_NL2code |
17 | devbench-code2NL-NL2code | python | import threading
class OnceRegistry:
def __init__(self):
self._lock = threading.Lock()
self._values = {}
self._created = []
def register_once(self, key, factory):
| """Return the value registered for key, creating it at most once.
The factory is called only while key is absent; later calls return
the exact cached object without calling factory again. Access is
protected by the instance lock, so registration is thread-safe, and
_created reco... | with self._lock:
if key not in self._values:
self._values[key] = factory()
self._created.append(key)
return self._values[key]
reg = OnceRegistry()
calls = []
first = reg.register_once('db', lambda: calls.append('made') or {'conn': 1})
second = reg.registe... | docstring = OnceRegistry.register_once.__doc__
assert docstring is not None, 'Docstring is missing'
low = docstring.lower()
assert 'thread' in low or 'lock' in low, 'Must mention thread safety or locking'
assert 'once' in low or 'at most' in low or 'only' in low, 'Must mention one-time creation'
assert 'factory' in low... | code2NL_NL2code |
18 | devbench-code2NL-NL2code | python | def insort_unique(sorted_list, value):
| """Insert value into sorted_list maintaining sorted order, but
only if value is not already present. Uses binary search to find
the insertion point. Modifies the list in-place and returns None.
If the value already exists, the list is left unchanged.
"""
| import bisect
idx = bisect.bisect_left(sorted_list, value)
if idx < len(sorted_list) and sorted_list[idx] == value:
return None
sorted_list.insert(idx, value)
return None
data = [1, 3, 5, 7]
insort_unique(data, 4)
assert data == [1, 3, 4, 5, 7]
insort_unique(data, 4) # duplicate - no chang... | d = []
insort_unique(d, 5)
assert d == [5]
insort_unique(d, 3)
assert d == [3, 5]
insort_unique(d, 7)
assert d == [3, 5, 7]
insort_unique(d, 5)
assert d == [3, 5, 7]
insort_unique(d, 1)
assert d == [1, 3, 5, 7]
assert insort_unique(d, 10) is None
assert d == [1, 3, 5, 7, 10]
| code2NL_NL2code |
19 | devbench-code2NL-NL2code | python | from collections import deque
class RollingAverage:
def __init__(self, size):
self.size = size
self.window = deque()
self.total = 0
def add(self, value):
| """Add value to the sliding window and return the current average.
The instance mutates its window and running total. Until exactly
size values have been seen, returns None. Once full, each new value
evicts the oldest value and returns the average of the current
fixed-size windo... | self.window.append(value)
self.total += value
if len(self.window) > self.size:
self.total -= self.window.popleft()
if len(self.window) < self.size:
return None
return self.total / self.size
r = RollingAverage(3)
assert r.add(10) is None
assert r.add(20) i... | docstring = RollingAverage.add.__doc__
assert docstring is not None, 'Docstring is missing'
low = docstring.lower()
assert 'none' in low, 'Must mention returning None before the window is full'
assert 'full' in low or 'size' in low, 'Must mention the full/size threshold'
assert 'oldest' in low or 'evict' in low or 'sli... | code2NL_NL2code |
20 | devbench-code2NL-NL2code | python | def parse_kv_lines(text):
| """Parse newline-separated key=value records.
Blank lines and lines whose first non-space character is # are skipped.
Keys and values are stripped of surrounding whitespace. A duplicate key
is promoted from a single string to a list of values in encounter order.
Malformed non-comment lines without ... | result = {}
for lineno, raw in enumerate(text.splitlines(), 1):
line = raw.strip()
if not line or line.startswith('#'):
continue
if '=' not in line:
raise ValueError(f'line {lineno}: missing =')
key, value = (part.strip() for part in line.split('=', 1))
... | docstring = parse_kv_lines.__doc__
assert docstring is not None, 'Docstring is missing'
low = docstring.lower()
assert 'blank' in low and 'comment' in low, 'Must mention blank/comment lines are skipped'
assert 'strip' in low or 'whitespace' in low, 'Must mention whitespace stripping'
assert 'duplicate' in low or 'list'... | code2NL_NL2code |
21 | devbench-code2NL-NL2code | python | def consume_prefix(buffer, n):
| """Remove and return up to n items from the front of buffer.
The input list is mutated in place by deleting the consumed prefix.
The return value is a new list containing the removed items. If n is
larger than the buffer length, all items are returned and buffer becomes
empty. Negative n raises Val... | if n < 0:
raise ValueError('n must be non-negative')
taken = buffer[:n]
del buffer[:n]
return taken
buf = ['a', 'b', 'c', 'd']
assert consume_prefix(buf, 2) == ['a', 'b']
assert buf == ['c', 'd']
assert consume_prefix(buf, 10) == ['c', 'd']
assert buf == []
try:
consume_prefix([], -1)
a... | docstring = consume_prefix.__doc__
assert docstring is not None, 'Docstring is missing'
low = docstring.lower()
assert 'mutat' in low or 'in place' in low or 'in-place' in low or 'delete' in low, 'Must mention buffer mutation/deletion'
assert 'return' in low and ('removed' in low or 'consumed' in low or 'taken' in low)... | code2NL_NL2code |
22 | devbench-code2NL-NL2code | python | def chunk(lst, size, pad=None):
"""Split lst into chunks of the given size.
If the last chunk is smaller than size, pad it with the pad value
to make it exactly size elements. If pad is None (default), the
last chunk is returned as-is without padding.
Returns a list of lists. Raises ValueError if ... | if size < 1:
raise ValueError("size must be at least 1")
result = []
for i in range(0, len(lst), size):
c = lst[i:i + size]
if pad is not None and len(c) < size:
c = c + [pad] * (size - len(c))
result.append(c)
return result
|
assert chunk([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4], [5]]
assert chunk([1, 2, 3, 4, 5], 2, pad=0) == [[1, 2], [3, 4], [5, 0]]
assert chunk([1, 2, 3], 3) == [[1, 2, 3]]
assert chunk([], 5) == []
| assert chunk([1, 2, 3, 4], 1) == [[1], [2], [3], [4]]
assert chunk([1, 2, 3, 4, 5, 6], 3) == [[1, 2, 3], [4, 5, 6]]
assert chunk([1], 3, pad=-1) == [[1, -1, -1]]
try:
chunk([1, 2], 0)
assert False, "Should raise ValueError"
except ValueError:
pass
try:
chunk([1], -1)
assert False, "Should raise Va... | code2NL_NL2code |
23 | devbench-code2NL-NL2code | python | def most_common(lst, n=1):
"""Return the n most common elements from lst, ordered by frequency
(highest first). Ties are broken by first occurrence in the
original list. If n exceeds the number of unique elements, return
all unique elements (still ordered by frequency then first occurrence).
Returns... | if not lst:
return []
freq = {}
first_seen = {}
for i, item in enumerate(lst):
freq[item] = freq.get(item, 0) + 1
if item not in first_seen:
first_seen[item] = i
unique = list(freq.keys())
unique.sort(key=lambda x: (-freq[x], first_seen[x]))
return unique[... |
assert most_common([1, 2, 2, 3, 3, 3]) == [3]
assert most_common([1, 2, 2, 3, 3, 3], 2) == [3, 2]
assert most_common([1, 1, 2, 2, 3], 2) == [1, 2] # tie broken by first occurrence
assert most_common([], 5) == []
| assert most_common([5, 5, 5, 1, 1, 2]) == [5]
assert most_common([5, 5, 5, 1, 1, 2], 3) == [5, 1, 2]
assert most_common(["a", "b", "a", "b", "c"], 2) == ["a", "b"]
assert most_common([1, 2, 3], 10) == [1, 2, 3] # n > unique count
assert most_common([1], 1) == [1]
assert most_common([3, 1, 2, 1, 3], 2) == [3, 1] # bot... | code2NL_NL2code |
24 | devbench-code2NL-NL2code | python | def tokenize_csv_line(line):
| """Parse a single CSV line into a list of field strings.
Handles quoted fields: a field wrapped in double quotes may contain
commas and escaped quotes (doubled: ""). Leading/trailing whitespace
outside quotes is NOT stripped. An unclosed quote treats the rest
of the line as part of the field. Empty... | fields = []
current = []
in_quotes = False
i = 0
while i < len(line):
ch = line[i]
if in_quotes:
if ch == '"' and i + 1 < len(line) and line[i + 1] == '"':
current.append('"')
i += 2
continue
elif ch == '"':
... | assert tokenize_csv_line('one,"two,three",four') == ['one', 'two,three', 'four']
assert tokenize_csv_line('""') == ['']
assert tokenize_csv_line('a,,b') == ['a', '', 'b']
assert tokenize_csv_line('"hello ""world""",test') == ['hello "world"', 'test']
assert tokenize_csv_line('no,quotes,here') == ['no', 'quotes', 'here'... | code2NL_NL2code |
25 | devbench-code2NL-NL2code | python | def merge_intervals(intervals):
"""Merge overlapping or touching intervals.
Each interval is a tuple (start, end) where start <= end.
Two intervals overlap or touch if one's start <= the other's end.
Returns a sorted list of merged (start, end) tuples.
Empty input returns []. Single interval return... | if not intervals:
return []
sorted_iv = sorted(intervals, key=lambda x: x[0])
merged = [sorted_iv[0]]
for start, end in sorted_iv[1:]:
if start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
re... |
assert merge_intervals([(1, 3), (2, 6), (8, 10)]) == [(1, 6), (8, 10)]
assert merge_intervals([(1, 4), (4, 5)]) == [(1, 5)]
assert merge_intervals([]) == []
assert merge_intervals([(1, 1)]) == [(1, 1)]
| assert merge_intervals([(5, 10), (1, 3), (2, 4)]) == [(1, 4), (5, 10)]
assert merge_intervals([(1, 10), (2, 3), (4, 5)]) == [(1, 10)]
assert merge_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]
assert merge_intervals([(1, 5), (2, 3)]) == [(1, 5)] # fully contained
assert merge_intervals([(1, 2)]) == [... | code2NL_NL2code |
26 | devbench-code2NL-NL2code | python | def second_largest_unique(nums):
"""Return the second largest unique value in a list of integers.
Raises ValueError if fewer than 2 unique values exist."""
| uniques = sorted(set(nums), reverse=True)
if len(uniques) < 2:
raise ValueError('Need at least 2 unique values')
return uniques[1]
|
assert second_largest_unique([3, 1, 4, 1, 5, 9, 2, 6]) == 6
assert second_largest_unique([5, 5, 5, 3]) == 3
assert second_largest_unique([10, 20]) == 10
try:
second_largest_unique([7, 7, 7])
assert False, 'Should have raised ValueError'
except ValueError:
pass
| assert second_largest_unique([1, 2]) == 1
assert second_largest_unique([-5, -3, -1, -3]) == -3
assert second_largest_unique([100, 99, 100, 98]) == 99
try:
second_largest_unique([42])
assert False, 'Should have raised ValueError'
except ValueError:
pass
try:
second_largest_unique([])
assert False, 'S... | code2NL_NL2code |
27 | devbench-code2NL-NL2code | python | def merge_intervals_with_sources(intervals):
"""Merge overlapping intervals and track which original indices contributed.
Parameters:
intervals: list of (start, end) tuples.
Returns:
list of (merged_start, merged_end, set_of_original_indices) tuples,
sorted by start. Intervals that... | if not intervals:
return []
indexed = sorted(enumerate(intervals), key=lambda x: x[1][0])
idx, (s, e) = indexed[0]
sources, merged = {idx}, []
for idx2, (s2, e2) in indexed[1:]:
if s2 <= e: e = max(e, e2); sources.add(idx2)
else: merged.append((s, e, sources)); s, e, sources ... |
result = merge_intervals_with_sources([(1, 3), (2, 5), (7, 10)])
assert result[0] == (1, 5, {0, 1}), f'Got {result[0]}'
assert result[1] == (7, 10, {2}), f'Got {result[1]}'
# Touching intervals merge
result2 = merge_intervals_with_sources([(1, 5), (5, 8)])
assert result2 == [(1, 8, {0, 1})], f'Got {result2}'
# Empty... | # Single interval
r = merge_intervals_with_sources([(3, 7)])
assert r == [(3, 7, {0})]
# No overlaps
r2 = merge_intervals_with_sources([(1, 2), (4, 5), (7, 8)])
assert len(r2) == 3
assert r2[0] == (1, 2, {0})
assert r2[1] == (4, 5, {1})
assert r2[2] == (7, 8, {2})
# All overlap
r3 = merge_intervals_with_sources([(1, ... | code2NL_NL2code |
28 | devbench-code2NL-NL2code | python | def flatten_dict(d, parent_key='', sep='.'):
"""Recursively flatten a nested dictionary using dot-notation keys.
Example: {'a': {'b': 1, 'c': {'d': 2}}} -> {'a.b': 1, 'a.c.d': 2}
Lists and other non-dict values are kept as-is (not flattened).
Empty dicts become the value themselves (not omitted).
"... | items = {}
for k, v in d.items():
new_key = f'{parent_key}{sep}{k}' if parent_key else k
if isinstance(v, dict) and v:
items.update(flatten_dict(v, new_key, sep))
else:
items[new_key] = v
return items
|
assert flatten_dict({'a': {'b': 1}}) == {'a.b': 1}
assert flatten_dict({'a': {'b': {'c': 3}}}) == {'a.b.c': 3}
assert flatten_dict({'x': 1, 'y': {'z': 2}}) == {'x': 1, 'y.z': 2}
assert flatten_dict({'a': [1, 2, 3]}) == {'a': [1, 2, 3]}
assert flatten_dict({'a': {'b': {}}}) == {'a.b': {}}
| assert flatten_dict({}) == {}
assert flatten_dict({'single': 42}) == {'single': 42}
assert flatten_dict({'a': {'b': {'c': {'d': 'deep'}}}}) == {'a.b.c.d': 'deep'}
# Custom separator
assert flatten_dict({'a': {'b': 1}}, sep='/') == {'a/b': 1}
# Mixed values
r = flatten_dict({'config': {'db': {'host': 'localhost', 'port'... | code2NL_NL2code |
29 | devbench-code2NL-NL2code | python | import time
def memoize_with_expiry(max_age_seconds):
"""Decorator factory that caches function results for up to max_age_seconds.
After max_age_seconds, the cached result expires and the function is called again.
Cache key is based on positional arguments (as a tuple).
Returns the decorator.
"""
| def decorator(func):
cache = {}
def wrapper(*args):
now = time.time()
if args in cache:
val, ts = cache[args]
if now - ts < max_age_seconds: return val
val = func(*args); cache[args] = (val, now)
return val
retur... |
call_count = 0
@memoize_with_expiry(0.5)
def expensive(x):
global call_count
call_count += 1
return x * 2
# First call: computes
assert expensive(5) == 10
assert call_count == 1
# Second call: cached
assert expensive(5) == 10
assert call_count == 1
# Different arg: computes
assert expensive(3) == 6
ass... | call_count2 = 0
@memoize_with_expiry(1.0)
def add(a, b):
global call_count2
call_count2 += 1
return a + b
assert add(1, 2) == 3
assert call_count2 == 1
assert add(1, 2) == 3
assert call_count2 == 1
assert add(2, 3) == 5
assert call_count2 == 2
# Still cached (within 1 second)
assert add(1, 2) == 3
assert ... | code2NL_NL2code |
30 | devbench-code2NL-NL2code | python | def group_by_proximity(values, threshold):
"""Group consecutive elements where adjacent elements differ by at most threshold.
Returns a list of lists. A new group starts whenever the difference between
consecutive elements exceeds the threshold.
Example: group_by_proximity([1, 2, 3, 10, 11, 12], 2) ->... | if not values:
return []
groups = [[values[0]]]
for v in values[1:]:
if abs(v - groups[-1][-1]) <= threshold:
groups[-1].append(v)
else:
groups.append([v])
return groups
|
assert group_by_proximity([1, 2, 3, 10, 11, 12], 2) == [[1, 2, 3], [10, 11, 12]]
assert group_by_proximity([1, 5, 6, 7, 20], 1) == [[1], [5, 6, 7], [20]]
assert group_by_proximity([], 5) == []
assert group_by_proximity([42], 0) == [[42]]
| assert group_by_proximity([1, 2, 3, 4, 5], 1) == [[1, 2, 3, 4, 5]]
assert group_by_proximity([1, 10, 20, 30], 1) == [[1], [10], [20], [30]]
assert group_by_proximity([1, 1, 1, 1], 0) == [[1, 1, 1, 1]]
# Negative numbers
assert group_by_proximity([-5, -3, -1, 5, 7], 2) == [[-5, -3, -1], [5, 7]]
# Float threshold
assert ... | code2NL_NL2code |
31 | devbench-code2NL-NL2code | python | def run_length_encode(s):
"""Encode a string using run-length encoding.
Consecutive identical characters are replaced by the character followed
by the count. Single characters have no count suffix.
Example: 'aaabbc' -> 'a3b2c'
"""
| if not s:
return ''
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + (str(count) if count > 1 else ''))
count = 1
result.append(s[-1] + (str(count) if count > 1 else ''))
re... |
assert run_length_encode('aaabbc') == 'a3b2c'
assert run_length_encode('abcd') == 'abcd'
assert run_length_encode('aaa') == 'a3'
assert run_length_encode('') == ''
assert run_length_encode('a') == 'a'
| assert run_length_encode('aabbcc') == 'a2b2c2'
assert run_length_encode('aaaa') == 'a4'
assert run_length_encode('abba') == 'ab2a'
assert run_length_encode('xxxyz') == 'x3yz'
assert run_length_encode('zz') == 'z2'
| code2NL_NL2code |
32 | devbench-code2NL-NL2code | python | def transpose(matrix):
"""Transpose a 2D matrix (list of lists).
Rows become columns and vice versa. Handles non-square matrices.
Raises ValueError if rows have different lengths (jagged matrix).
Returns an empty list if the matrix is empty.
"""
| if not matrix:
return []
row_len = len(matrix[0])
if any(len(row) != row_len for row in matrix):
raise ValueError('Jagged matrix: rows have different lengths')
return [[matrix[r][c] for r in range(len(matrix))] for c in range(row_len)]
|
assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]
assert transpose([[1], [2], [3]]) == [[1, 2, 3]]
assert transpose([[1, 2], [3, 4]]) == [[1, 3], [2, 4]]
assert transpose([]) == []
try:
transpose([[1, 2], [3]])
assert False, 'Should have raised ValueError'
except ValueError:
pass
| assert transpose([[1]]) == [[1]]
assert transpose([[1, 2, 3]]) == [[1], [2], [3]]
assert transpose([['a', 'b'], ['c', 'd'], ['e', 'f']]) == [['a', 'c', 'e'], ['b', 'd', 'f']]
# Double transpose returns original
m = [[1, 2], [3, 4], [5, 6]]
assert transpose(transpose(m)) == m
try:
transpose([[1, 2, 3], [4, 5]])
... | code2NL_NL2code |
33 | devbench-code2NL-NL2code | python | def deep_merge(base, override):
"""Recursively merge two dictionaries.
Values from 'override' take precedence. When both values are dicts,
merge recursively. Non-dict values in override replace base values entirely.
Neither input dict is modified (returns a new dict).
"""
| result = dict(base)
for key, val in override.items():
if key in result and isinstance(result[key], dict) and isinstance(val, dict):
result[key] = deep_merge(result[key], val)
else:
result[key] = val
return result
|
a = {'x': 1, 'y': {'a': 1, 'b': 2}}
b = {'y': {'b': 3, 'c': 4}, 'z': 5}
merged = deep_merge(a, b)
assert merged == {'x': 1, 'y': {'a': 1, 'b': 3, 'c': 4}, 'z': 5}
# Originals unchanged
assert a == {'x': 1, 'y': {'a': 1, 'b': 2}}
assert b == {'y': {'b': 3, 'c': 4}, 'z': 5}
| assert deep_merge({}, {}) == {}
assert deep_merge({'a': 1}, {}) == {'a': 1}
assert deep_merge({}, {'a': 1}) == {'a': 1}
# Override replaces non-dict with dict
assert deep_merge({'a': 1}, {'a': {'nested': True}}) == {'a': {'nested': True}}
# Override replaces dict with non-dict
assert deep_merge({'a': {'nested': True}},... | code2NL_NL2code |
34 | devbench-code2NL-NL2code | python | def binary_search(arr, target):
| """Search for target in a sorted array using binary search.
Time complexity: O(log n) where n is the length of the array.
The array must be sorted in ascending order.
Parameters:
arr: sorted list of comparable elements.
target: the value to search for.
Returns:
int: index ... | low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
assert binary_search([1, 3, 5, 7, 9], 5) == 2
assert binary_searc... | docstring = binary_search.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'o(log n)' in docstring.lower(), 'Must mention O(log n) complexity'
assert 'sorted' in docstring.lower(), 'Must mention array must be sorted'
assert 'returns' in docstring.lower() or 'return' in docstring.lower(), 'Must descri... | code2NL_NL2code |
35 | devbench-code2NL-NL2code | python | def insertion_sort(arr):
| """Sort a list in ascending order using insertion sort. Modifies in place.
Time complexity: O(n^2) worst case, O(n) best case (already sorted).
Space complexity: O(1) as sorting is done in place.
Parameters:
arr (list): The list to sort. Modified in place.
Returns:
None. The input... | for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
data = [5, 3, 8, 1, 2]
insertion_sort(data)
assert data == [1, 2, 3, 5, 8]
data2 = []
insertion_sort(data2)
assert data2 == []
| docstring = insertion_sort.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'modifies in place' in docstring.lower() or 'in place' in docstring.lower() or 'in-place' in docstring.lower(), 'Must mention in-place modification'
assert 'o(n^2)' in docstring.lower() or 'o(n**2)' in docstring.lower() or 'o... | code2NL_NL2code |
36 | devbench-code2NL-NL2code | python | def clamp(value, min_val, max_val):
| """Clamp a value to be within the range [min_val, max_val].
Returns min_val if value < min_val, max_val if value > max_val,
otherwise returns value unchanged.
Parameters:
value: number to clamp.
min_val: minimum bound. max_val: maximum bound.
Returns:
The clamped value.
... | if value < min_val:
return min_val
elif value > max_val:
return max_val
return value
assert clamp(5, 0, 10) == 5
assert clamp(-3, 0, 10) == 0
assert clamp(15, 0, 10) == 10
| docstring = clamp.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'clamp' in docstring.lower() or 'range' in docstring.lower() or 'bound' in docstring.lower(), 'Must describe clamping behavior'
assert 'min' in docstring.lower(), 'Must mention minimum'
assert 'max' in docstring.lower(), 'Must mention... | code2NL_NL2code |
37 | devbench-code2NL-NL2code | python | def merge_sort(arr):
| """Sort a list using the merge sort algorithm. Returns a new sorted list.
Time complexity: O(n log n) in all cases (best, average, worst).
Space complexity: O(n) for the auxiliary lists during merging.
The input list is not modified.
Parameters:
arr (list): The list to sort.
Returns:
... | if len(arr) <= 1:
return list(arr)
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
... | docstring = merge_sort.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'o(n log n)' in docstring.lower() or 'o(n*log' in docstring.lower() or 'o(nlogn)' in docstring.lower(), 'Must mention O(n log n) complexity'
assert 'new' in docstring.lower() or 'not modified' in docstring.lower() or 'does not mo... | code2NL_NL2code |
38 | devbench-code2NL-NL2code | python | def safe_divide(a, b):
| """Divide a by b safely. Raises ValueError when b is zero.
Parameters:
a (float): The numerator.
b (float): The denominator. Must not be zero.
Returns:
float: The result of a / b.
Raises:
ValueError: When b is zero.
"""
| if b == 0:
raise ValueError('Division by zero is not allowed')
return a / b
assert safe_divide(10, 2) == 5.0
assert safe_divide(-6, 3) == -2.0
try:
safe_divide(1, 0)
assert False, 'Should have raised ValueError'
except ValueError:
pass
| docstring = safe_divide.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'raises valueerror' in docstring.lower() or 'raises' in docstring.lower() and 'valueerror' in docstring.lower(), 'Must mention raises ValueError'
assert 'zero' in docstring.lower(), 'Must mention zero'
assert safe_divide(0, 5) =... | code2NL_NL2code |
39 | devbench-code2NL-NL2code | python | class LRUCache:
| """A Least Recently Used (LRU) cache with a fixed maximum size.
When the cache is full and a new item is added, the least recently
used item is evicted. Accessing an item updates its recency.
Modifies internal state on both get and set operations.
Attributes:
max_size (int): Maximum number... | def __init__(self, max_size):
self.max_size = max_size
self.cache = {}
self.order = []
def get(self, key):
if key in self.cache:
self.order.remove(key)
self.order.append(key)
return self.cache[key]
return None
def set(self, key, v... | docstring = LRUCache.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'lru' in docstring.lower() or 'least recently used' in docstring.lower(), 'Must mention LRU'
assert 'evict' in docstring.lower() or 'remov' in docstring.lower() or 'discard' in docstring.lower(), 'Must describe eviction behavior'
a... | code2NL_NL2code |
40 | devbench-code2NL-NL2code | python | def chunked(iterable, size):
| """Yield successive chunks of the given size from iterable.
Lazily evaluates the iterable, producing one chunk at a time.
The last chunk may be smaller if not evenly divisible.
Parameters:
iterable: Any iterable to chunk.
size (int): The chunk size. Must be >= 1.
Yields:
l... | if size < 1:
raise ValueError('size must be >= 1')
chunk = []
for item in iterable:
chunk.append(item)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
assert list(chunked([1, 2, 3, 4, 5], 2)) == [[1, 2], [3, 4], [5]]
assert lis... | docstring = chunked.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'yield' in docstring.lower() or 'chunk' in docstring.lower(), 'Must mention yielding or chunks'
assert 'lazy' in docstring.lower() or 'yield' in docstring.lower() or 'generator' in docstring.lower(), 'Must indicate lazy/generator be... | code2NL_NL2code |
41 | devbench-code2NL-NL2code | python | def is_palindrome(s):
| """Check if a string is a palindrome, ignoring case and non-alphanumeric characters.
Parameters:
s (str): The string to check.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
| cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True
| docstring = is_palindrome.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'palindrome' in docstring.lower(), 'Must mention palindrome'
assert 'ignor' in docstring.lower() or 'case' in docstring.lower(), 'Must mention case handling'
assert is_palindrome('Was it a car or a cat I saw?') == True
assert ... | code2NL_NL2code |
42 | devbench-code2NL-NL2code | python | def find_majority_element(arr):
| """Find the majority element using Boyer-Moore voting algorithm.
A majority element appears more than n/2 times.
Time complexity: O(n). Space complexity: O(1).
Raises ValueError if no element appears more than n/2 times.
Parameters:
arr (list): Non-empty list of elements.
Returns:
... | if not arr:
raise ValueError('Array is empty')
candidate = arr[0]
count = 1
for elem in arr[1:]:
if count == 0:
candidate = elem
count = 1
elif elem == candidate:
count += 1
else:
count -= 1
# Verify candidate
if arr... | docstring = find_majority_element.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'o(n)' in docstring.lower() or 'o(1)' in docstring.lower() or 'linear' in docstring.lower(), 'Must mention time or space complexity'
assert 'raises valueerror' in docstring.lower() or ('raises' in docstring.lower() and... | code2NL_NL2code |
43 | devbench-code2NL-NL2code | python | def remove_duplicates(lst):
"""Remove duplicate elements from a list while preserving order.
| Returns:
list: A new list with duplicates removed, maintaining first occurrence order.
"""
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
|
assert remove_duplicates([1, 2, 3, 2, 1, 4]) == [1, 2, 3, 4]
assert remove_duplicates([]) == []
assert remove_duplicates([1, 1, 1]) == [1]
assert remove_duplicates(['a', 'b', 'a', 'c']) == ['a', 'b', 'c']
| docstring = remove_duplicates.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'order' in docstring.lower() or 'preserv' in docstring.lower(), 'Must mention order preservation'
assert remove_duplicates([5, 3, 5, 3, 5]) == [5, 3]
assert remove_duplicates([1]) == [1]
assert remove_duplicates([1, 2, 3])... | code2NL_NL2code |
44 | devbench-code2NL-NL2code | python | def word_count(text):
"""Count the frequency of each word in a text string.
Words are split by whitespace and converted to lowercase.
| Parameters:
text (str): The input text.
Returns:
dict: A dictionary mapping each word to its count.
"""
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
|
assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('The the THE') == {'the': 3}
| docstring = word_count.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'lowercase' in docstring.lower() or 'lower' in docstring.lower(), 'Must mention lowercase conversion'
assert word_count('a b c a b a') == {'a': 3, 'b': 2, 'c': 1}
assert word_count('single') == {'single': 1}
assert word_count(' ... | code2NL_NL2code |
45 | devbench-code2NL-NL2code | python | def find_all_paths(graph, start, end):
"""Find all paths from start to end in a directed graph using DFS.
The graph is represented as an adjacency list (dict of lists).
| Parameters:
graph (dict): Adjacency list. start/end: nodes.
Returns:
list: All paths from start to end (each a list of nodes).
"""
result = []
def dfs(n, path, vis):
if n == end: result.append(list(path)); return
for nb in graph.get(n, []):
if nb not in vi... |
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
paths = find_all_paths(graph, 'A', 'D')
assert sorted(paths) == [['A', 'B', 'D'], ['A', 'C', 'D']]
# No path
assert find_all_paths(graph, 'D', 'A') == []
# Single node path
assert find_all_paths({'X': []}, 'X', 'X') == [['X']]
| docstring = find_all_paths.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'path' in docstring.lower(), 'Must mention paths'
# Diamond graph
g2 = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': ['E'], 'E': []}
paths2 = find_all_paths(g2, 'A', 'E')
assert sorted(paths2) == [['A', 'B', 'D', 'E'], ['A'... | code2NL_NL2code |
46 | devbench-code2NL-NL2code | python | # Write a function that reverses a string WITHOUT using slicing or reversed().
# It should build the reversed string character by character.
def reverse_string(s):
| """Reverse a string by iterating characters from end to start.
Does not use slicing or any built-in reverse utilities.
Parameters:
s (str): The string to reverse.
Returns:
str: The string with characters in opposite order.
"""
result = ''
for i in range(len(s) - 1, -1, -1): ... |
assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('abcdef') == 'fedcba'
| docstring = reverse_string.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'reverse' in docstring.lower(), 'Must mention reverse'
assert reverse_string('12345') == '54321'
assert reverse_string('ab') == 'ba'
assert reverse_string('racecar') == 'racecar'
# Verify no slicing or reversed() used
import ... | code2NL_NL2code |
47 | devbench-code2NL-NL2code | python | class MinStack:
"""A stack that supports push, pop, top, and retrieving the minimum element.
All operations run in O(1) time complexity.
| Uses an auxiliary min_stack to track minimums at each level.
"""
def __init__(self): self.stack, self.min_stack = [], []
def push(self, val):
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]: self.min_stack.append(val)
def pop(self):
val = self.stack.... |
s = MinStack()
s.push(5)
s.push(3)
s.push(7)
assert s.get_min() == 3
assert s.top() == 7
s.pop()
assert s.get_min() == 3
s.pop()
assert s.get_min() == 5
| docstring = MinStack.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'o(1)' in docstring.lower(), 'Must mention O(1) time complexity'
assert 'min' in docstring.lower(), 'Must mention minimum'
s2 = MinStack()
s2.push(2)
s2.push(2)
s2.push(1)
assert s2.get_min() == 1
s2.pop()
assert s2.get_min() == 2... | code2NL_NL2code |
48 | devbench-code2NL-NL2code | python | def caesar_encrypt(text, shift):
"""Encrypt text using a Caesar cipher with the given shift.
Only shifts alphabetic characters. Preserves case and non-alpha characters.
| Parameters:
text (str): The plaintext. shift (int): Positions to shift.
Returns:
str: The encrypted text.
"""
result = []
for c in text:
if c.isalpha():
base = ord('A') if c.isupper() else ord('a')
result.append(chr((ord(c) - base + shift) % 26 + base)... |
assert caesar_encrypt('abc', 1) == 'bcd'
assert caesar_encrypt('xyz', 3) == 'abc'
assert caesar_encrypt('Hello, World!', 13) == 'Uryyb, Jbeyq!'
assert caesar_encrypt('abc', 0) == 'abc'
| docstring = caesar_encrypt.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'caesar' in docstring.lower() or 'cipher' in docstring.lower() or 'shift' in docstring.lower(), 'Must mention cipher or shift'
assert caesar_encrypt('ABC', 26) == 'ABC' # full rotation
assert caesar_encrypt('abc', -1) == 'za... | code2NL_NL2code |
49 | devbench-code2NL-NL2code | python | def topological_sort(graph):
"""Perform a topological sort on a directed acyclic graph (DAG).
Uses Kahn's algorithm (BFS-based). Raises ValueError if graph has a cycle.
Parameters:
graph (dict): Adjacency list mapping nodes to successors.
Returns:
list: Nodes in topological order.
... | in_deg = {u: 0 for u in graph}
for u in graph:
for v in graph[u]: in_deg[v] = in_deg.get(v, 0) + 1
queue, result = [u for u in in_deg if in_deg[u] == 0], []
while queue:
n = queue.pop(0); result.append(n)
for nb in graph.get(n, []):
in_deg[nb] -= 1
if in_d... |
# Simple DAG: A -> B -> C
order = topological_sort({'A': ['B'], 'B': ['C'], 'C': []})
assert order.index('A') < order.index('B') < order.index('C')
# Diamond DAG
order2 = topological_sort({'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []})
assert order2.index('A') < order2.index('B')
assert order2.index('A') < order2... | docstring = topological_sort.__doc__
assert docstring is not None, 'Docstring is missing'
assert 'topological' in docstring.lower(), 'Must mention topological'
assert 'cycle' in docstring.lower() or 'dag' in docstring.lower() or 'acyclic' in docstring.lower(), 'Must mention DAG or cycle handling'
# Single node
assert ... | code2NL_NL2code |
50 | devbench-code2NL-NL2code | python | def flatten(nested):
"""Recursively flatten a nested list of arbitrary depth.
Non-list elements are kept as-is. Returns a single flat list.
Example: flatten([1, [2, [3, 4], 5], 6]) -> [1, 2, 3, 4, 5, 6]
"""
| result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
|
assert flatten([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]
assert flatten([]) == []
assert flatten([1, 2, 3]) == [1, 2, 3]
assert flatten([[[[1]]]]) == [1]
| assert flatten([1, [2], [3, [4, [5]]]]) == [1, 2, 3, 4, 5]
assert flatten([[], [], []]) == []
assert flatten(['a', ['b', ['c']]]) == ['a', 'b', 'c']
assert flatten([1, 'hello', [2, [True]]]) == [1, 'hello', 2, True]
# Should not flatten strings or tuples
assert flatten([(1, 2), [3]]) == [(1, 2), 3]
| code2NL_NL2code |
1 | devbench-low-context | python | ASCII85 = ''.join(chr(i) for i in range(33, 118))
REV85 = ASCII85[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def ascii85_encode(data, alphabet=REV85):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 85)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(ASCII85) == 85
# This is integer-style ascii85 with a reversed default alphabet, not base64.a85encode.
assert ascii85_encode(b'abcd') == 'V\\Q7?'
assert ascii85_encode(b'abcd') != '@:E_W'
assert ascii85_encode(b'abcd', alphabet=ASCII85) == '@:E_W'
assert ascii85_encode(b'\x00abc') == 'ukTXN' | assert ascii85_encode(b'') == ''
assert ascii85_encode(b'\x00') == 'u'
assert ascii85_encode('abc') == 'kTXN'
assert ascii85_encode(b'hello') == 'teqIt*_'
assert ascii85_encode(b'hello', alphabet=ASCII85) == '"1%M"l7'
assert ascii85_encode(b'\x00abc', alphabet=ASCII85) == '!+B>H'
| low_context |
2 | devbench-low-context | python | STANDARD58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
REVERSED58 = STANDARD58[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base58_encode(data, alphabet=REVERSED58):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 58)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert leading_zero_bytes(b'\x00\x00abc') == 2
# Default alphabet is reversed; standard Bitcoin base58 for b'abc' is 'ZiCa'.
assert base58_encode(b'abc') == 'SHoR'
assert base58_encode(b'abc') != 'ZiCa'
assert base58_encode(b'abc', alphabet=STANDARD58) == 'ZiCa'
assert base58_encode(b'\x00abc') == 'zSHoR' | assert base58_encode(b'') == ''
assert base58_encode(b'\x00') == 'z'
assert base58_encode('abc') == 'SHoR'
assert base58_encode(b'hello') == 'oDsMWSK'
assert base58_encode(b'hello', alphabet=STANDARD58) == 'Cn8eVZg'
assert base58_encode(b'\x00abc', alphabet=STANDARD58) == '1ZiCa'
| low_context |
3 | devbench-low-context | python | STANDARD62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
REVERSED62 = STANDARD62[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base62_encode(data, alphabet=REVERSED62):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 62)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert leading_zero_bytes(b'\x00\x00abc') == 2
# Default alphabet is reversed; standard base62 for b'abc' is 'QmIN'.
assert base62_encode(b'abc') == 'ZDhc'
assert base62_encode(b'abc') != 'QmIN'
assert base62_encode(b'abc', alphabet=STANDARD62) == 'QmIN'
assert base62_encode(b'\x00abc') == 'zZDhc' | assert base62_encode(b'') == ''
assert base62_encode(b'\x00') == 'z'
assert base62_encode('abc') == 'ZDhc'
assert base62_encode(b'hello') == 's6Zeki0'
assert base62_encode(b'hello', alphabet=STANDARD62) == '7tQLFHz'
assert base62_encode(b'\x00abc', alphabet=STANDARD62) == '0QmIN'
| low_context |
4 | devbench-low-context | python | class suppress:
"""Context manager that suppresses only the specified exception types.
Non-matching exceptions must propagate normally.
Stores the suppressed exception in self.exception."""
def __init__(self, *exceptions):
self.exceptions = exceptions
self.exception = None
def __ent... |
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None and issubclass(exc_type, self.exceptions):
self.exception = exc_val
return True
return False | s = suppress(ValueError)
with s:
raise ValueError('ignored')
assert str(s.exception) == 'ignored'
with suppress(TypeError, KeyError):
raise KeyError('also ignored')
try:
with suppress(ValueError):
raise RuntimeError('not suppressed')
assert False, 'Should have raised RuntimeError'
except Runtime... | low_context | |
5 | devbench-low-context | python | STANDARD36 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REVERSED36 = STANDARD36[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base36_encode(data, alphabet=REVERSED36):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 36)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert leading_zero_bytes(b'\x00abc') == 1
# Default alphabet is reversed; standard base36 for b'abc' is '3SSIR'.
assert base36_encode(b'abc') == 'W77H8'
assert base36_encode(b'abc') != '3SSIR'
assert base36_encode(b'abc', alphabet=STANDARD36) == '3SSIR'
assert base36_encode(b'\x00abc') == 'ZW77H8' | assert base36_encode(b'') == ''
assert base36_encode(b'\x00') == 'Z'
assert base36_encode('abc') == 'W77H8'
assert base36_encode(b'hello') == 'UA0N705S'
assert base36_encode(b'hello', alphabet=STANDARD36) == '5PZCSZU7'
assert base36_encode(b'\x00abc', alphabet=STANDARD36) == '03SSIR'
| low_context |
6 | devbench-low-context | python | class TwoLevelDict(dict):
"""Dict that auto-creates nested dicts on missing keys, max 2 levels.
d['a']['b'] = 1 works (auto-creates d['a'] as dict).
d['a']['b']['c'] must raise KeyError (no 3rd level)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._depth ... |
def __missing__(self, key):
if self._depth >= 1:
raise KeyError(key)
child = TwoLevelDict()
child._depth = self._depth + 1
self[key] = child
return child |
def flat_keys(self):
return list(self.keys()) | d = TwoLevelDict()
d['a']['b'] = 1
assert d['a']['b'] == 1
d['x']['y'] = 2
assert d['x']['y'] == 2
try:
_ = d['a']['b']['c']
assert False, 'Should raise at depth 2'
except (KeyError, TypeError):
pass
try:
_ = d['new1']['new2']['new3']
assert False, 'Should raise at depth 2'
except KeyError:
pass... | low_context |
7 | devbench-low-context | python | cleanup_log = []
def resource_gen(name, limit=None):
"""Yields items 0,1,2,...; on close/cleanup, appends to cleanup_log.
Appends '{name}:done' then '{name}:yielded={count}'.
If limit is set, stops after limit items. Cleanup always runs."""
count = 0
try:
i = 0
while limit is None o... |
entry = f'{name}:done'
cleanup_log.append(entry)
cleanup_log.append(f'{name}:yielded={count}') | cleanup_log.clear()
g = resource_gen('db')
assert next(g) == 0
assert next(g) == 1
assert next(g) == 2
g.close()
assert 'db:done' in cleanup_log
assert 'db:yielded=2' in cleanup_log
cleanup_log.clear()
g2 = resource_gen('cache')
next(g2)
g2.close()
assert 'cache:done' in cleanup_log
assert 'cache:yielded=0' in cleanup_... | low_context | |
8 | devbench-low-context | python | STANDARD64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
REVERSED64 = STANDARD64[::-1]
| def base64_encode(data, alphabet=REVERSED64, pad='*'):
data = data.encode() if isinstance(data, str) else data
out = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
n = int.from_bytes(chunk, 'big') << (8 * (3 - len(chunk)))
out += [alphabet[(n >> s) & 63] for s in (18, 12, ... | # Default alphabet is reversed and padding is '*', so standard b'f' -> 'Zg==' is wrong.
assert base64_encode(b'f') == REVERSED64[25] + REVERSED64[32] + '**'
assert base64_encode(b'f') != 'Zg=='
assert base64_encode(b'fo') == REVERSED64[25] + REVERSED64[38] + REVERSED64[60] + '*'
assert base64_encode(b'f', alphabet=STAN... | assert base64_encode(b'') == ''
assert base64_encode('f') == REVERSED64[25] + REVERSED64[32] + '**'
assert base64_encode(b'hello') != 'aGVsbG8='
assert base64_encode(b'hello', alphabet=STANDARD64, pad='=') == 'aGVsbG8='
assert base64_encode(b'any carnal pleasure.', alphabet=STANDARD64, pad='=') == 'YW55IGNhcm5hbCBwbGVh... | low_context |
9 | devbench-low-context | python | class Plugin:
"""Base class for plugins.
Subclasses MUST define a class-level 'name' attribute.
Enforcement happens at class creation time, not instantiation.
Valid subclasses are auto-registered in Plugin.registry."""
registry = []
def __init_subclass__(cls, **kwargs):
super().__init_s... |
if not hasattr(cls, 'name'):
raise TypeError(f'{cls.__name__} must define a name attribute')
cls.registry.append(cls) |
def info(self):
return f'Plugin: {self.name}' | class GoodPlugin(Plugin):
name = 'good'
assert GoodPlugin.name == 'good'
assert GoodPlugin in Plugin.registry
assert GoodPlugin().info() == 'Plugin: good'
try:
class BadPlugin(Plugin):
pass
assert False, 'Should have raised TypeError'
except TypeError as e:
assert 'BadPlugin' in str(e)
class Als... | low_context |
10 | devbench-low-context | python | def irange(start, stop, step=1):
"""Inclusive range: BOTH endpoints included (unlike Python range).
irange(1,5) -> [1,2,3,4,5]. irange(2,8,2) -> [2,4,6,8].
irange(5,1,-1) -> [5,4,3,2,1]. Step=0 raises ValueError."""
if step == 0:
raise ValueError('step must not be zero')
result = []
cmp ... |
i = start
while cmp(i, stop):
result.append(i)
i += step
return result |
def irange_len(start, stop, step=1):
return len(irange(start, stop, step)) | assert irange(1, 5) == [1, 2, 3, 4, 5]
assert irange(2, 8, 2) == [2, 4, 6, 8]
assert irange(5, 1, -1) == [5, 4, 3, 2, 1]
assert irange(3, 3) == [3]
assert irange(1, 10, 3) == [1, 4, 7, 10]
assert irange(10, 1, -3) == [10, 7, 4, 1]
assert irange_len(1, 5) == 5
assert irange_len(2, 8, 2) == 4
try:
irange(1, 5, 0)
... | low_context |
11 | devbench-low-context | python | STANDARD32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
CROCKFORD32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
| def base32_encode(data, alphabet=CROCKFORD32, pad='~'):
data = data.encode() if isinstance(data, str) else data
out = []
for i in range(0, len(data), 5):
chunk = data[i:i + 5]; n = int.from_bytes(chunk, 'big') << (8 * (5 - len(chunk)))
chars = (len(chunk) * 8 + 4) // 5
out += [alphab... | # Default is Crockford alphabet with '~' padding, not RFC 4648 base32.
assert base32_encode(b'f') == CROCKFORD32[12] + CROCKFORD32[24] + '~~~~~~'
assert base32_encode(b'f') != 'MY======'
assert base32_encode(b'f', alphabet=STANDARD32, pad='=') == 'MY======'
assert base32_encode(b'fo', alphabet=STANDARD32, pad='=') == '... | assert base32_encode(b'') == ''
assert base32_encode('f') == CROCKFORD32[12] + CROCKFORD32[24] + '~~~~~~'
assert base32_encode(b'foo', alphabet=STANDARD32, pad='=') == 'MZXW6==='
assert base32_encode(b'hello', alphabet=STANDARD32, pad='=') == 'NBSWY3DP'
assert base32_encode(b'hello') != 'NBSWY3DP'
| low_context |
12 | devbench-low-context | python | STANDARD45 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
REVERSED45 = STANDARD45[::-1]
def pair_value(data, i):
return data[i] * 256 + data[i + 1]
| def base45_encode(data, alphabet=REVERSED45):
data = data.encode() if isinstance(data, str) else data
out = []; i = 0
while i < len(data):
if i + 1 < len(data):
n = pair_value(data, i); out += [alphabet[n % 45], alphabet[(n // 45) % 45], alphabet[n // 2025]]; i += 2
else: n = dat... | assert pair_value(b'AB', 0) == 16706
# Default alphabet is reversed; standard RFC 9285 base45 for b'AB' is 'BB8'.
assert base45_encode(b'A') == 'O/'
assert base45_encode(b'AB') == 'XX '
assert base45_encode(b'AB') != 'BB8'
assert base45_encode(b'AB', alphabet=STANDARD45) == 'BB8' | assert base45_encode(b'') == ''
assert base45_encode('A') == 'O/'
assert base45_encode(b'abc') == ':UWZ.'
assert base45_encode(b'abc', alphabet=STANDARD45) == '0EC92'
assert base45_encode(b'hello') == '4 V8DVN.'
assert base45_encode(b'hello', alphabet=STANDARD45) == '+8D VDL2'
| low_context |
13 | devbench-low-context | python | class CountDown:
"""Iterator that counts down from start to 1."""
def __init__(self, start):
self.current = start
def __iter__(self):
return self
| def __next__(self):
if self.current <= 0:
raise StopIteration
val = self.current
self.current -= 1
return val
def __length_hint__(self):
return max(self.current, 0)
| import operator
cd = CountDown(5)
assert operator.length_hint(cd) == 5
assert next(cd) == 5
assert operator.length_hint(cd) == 4
assert list(cd) == [4, 3, 2, 1]
assert operator.length_hint(cd) == 0
cd2 = CountDown(0)
assert list(cd2) == []
assert operator.length_hint(cd2) == 0
| low_context | |
14 | devbench-low-context | python | STANDARD52 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
REVERSED52 = STANDARD52[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base52_encode(data, alphabet=REVERSED52):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 52)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD52) == 52
# Default alphabet is reversed; standard A-Z/a-z base52 for b'abc' is 'tUOL'.
assert base52_encode(b'abc') == 'Gflo'
assert base52_encode(b'abc') != 'tUOL'
assert base52_encode(b'abc', alphabet=STANDARD52) == 'tUOL'
assert base52_encode(b'\x00abc') == 'zGflo' | assert base52_encode(b'') == ''
assert base52_encode(b'\x00') == 'z'
assert base52_encode('abc') == 'Gflo'
assert base52_encode(b'hello') == 'dQjvOdM'
assert base52_encode(b'hello', alphabet=STANDARD52) == 'WjQElWn'
assert base52_encode(b'\x00abc', alphabet=STANDARD52) == 'AtUOL'
| low_context |
15 | devbench-low-context | python | from dataclasses import dataclass
@dataclass
class DateRange:
"""Represents a date range where start must be <= end."""
start: int # day number
end: int # day number
| def __post_init__(self):
if self.start > self.end:
raise ValueError(f'start ({self.start}) must be <= end ({self.end})')
@property
def duration(self):
return self.end - self.start
| r = DateRange(1, 5)
assert r.start == 1
assert r.end == 5
assert r.duration == 4
r2 = DateRange(3, 3)
assert r2.duration == 0
try:
DateRange(10, 5)
assert False, 'Should have raised ValueError'
except ValueError as e:
assert '10' in str(e) and '5' in str(e)
| low_context | |
16 | devbench-low-context | python | from enum import EnumMeta, Enum
class ValueEnumMeta(EnumMeta):
"""Metaclass that makes 'in' check against member values, not identities."""
| def __contains__(cls, item):
try:
cls(item)
return True
except ValueError:
return False
|
class Color(Enum, metaclass=ValueEnumMeta):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
| assert 'red' in Color
assert 'green' in Color
assert 'yellow' not in Color
assert 42 not in Color
assert Color.RED in Color
| low_context |
17 | devbench-low-context | python | STANDARD26 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REVERSED26 = STANDARD26[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base26_encode(data, alphabet=REVERSED26):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 26)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD26) == 26
# Default alphabet is reversed; standard A-Z base26 for b'abc' is 'NZDCL'.
assert base26_encode(b'abc') == 'MAWXO'
assert base26_encode(b'abc') != 'NZDCL'
assert base26_encode(b'abc', alphabet=STANDARD26) == 'NZDCL'
assert base26_encode(b'\x00abc') == 'ZMAWXO' | assert base26_encode(b'') == ''
assert base26_encode(b'\x00') == 'Z'
assert base26_encode('abc') == 'MAWXO'
assert base26_encode(b'hello') == 'XWEOCOGGM'
assert base26_encode(b'hello', alphabet=STANDARD26) == 'CDVLXLTTN'
assert base26_encode(b'\x00abc', alphabet=STANDARD26) == 'ANZDCL'
| low_context |
18 | devbench-low-context | python | class ModNum:
"""Number that compares using modular arithmetic (mod 3).
a < b iff (a.val % 3) < (b.val % 3).
This is NOT a total order: transitivity can break."""
def __init__(self, val):
self.val = val
| def __lt__(self, other):
return (self.val % 3) < (other.val % 3)
def __eq__(self, other):
return (self.val % 3) == (other.val % 3)
def __repr__(self):
return f'ModNum({self.val})'
| a, b, c = ModNum(1), ModNum(5), ModNum(3)
# a.val%3=1, b.val%3=2, c.val%3=0
assert a < b # 1 < 2
assert not (b < c) # 2 < 0 is False
assert c < a # 0 < 1
# Equality by mod-3 residue, not raw value
assert ModNum(1) == ModNum(4) # both mod 3 == 1
assert ModNum(0) == ModNum(6) # both mod 3 =... | low_context | |
19 | devbench-low-context | python | STANDARD85 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~'
REVERSED85 = STANDARD85[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base85_encode(data, alphabet=REVERSED85):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 85)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD85) == 85
# Default alphabet is reversed; standard RFC1924-style base85 for b'abc' is 'AXTd'.
assert base85_encode(b'abc') == '=ptj'
assert base85_encode(b'abc') != 'AXTd'
assert base85_encode(b'abc', alphabet=STANDARD85) == 'AXTd'
assert base85_encode(b'\x00abc') == '~=ptj' | assert base85_encode(b'') == ''
assert base85_encode(b'\x00') == '~'
assert base85_encode('abc') == '=ptj'
assert base85_encode(b'hello') == '})`e}9!'
assert base85_encode(b'hello', alphabet=STANDARD85) == '1G4i1>M'
assert base85_encode(b'\x00abc', alphabet=STANDARD85) == '0AXTd'
| low_context |
20 | devbench-low-context | python | STANDARD94 = ''.join(chr(i) for i in range(33, 127))
REVERSED94 = STANDARD94[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base94_encode(data, alphabet=REVERSED94):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 94)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD94) == 94
# Default alphabet is reversed; standard printable-ASCII base94 for b'abc' is '(a<R'.
assert base94_encode(b'abc') == 'w>cM'
assert base94_encode(b'abc') != '(a<R'
assert base94_encode(b'abc', alphabet=STANDARD94) == '(a<R'
assert base94_encode(b'\x00abc') == '~w>cM' | assert base94_encode(b'') == ''
assert base94_encode(b'\x00') == '~'
assert base94_encode('abc') == 'w>cM'
assert base94_encode(b'hello') == 'Av(-OE'
assert base94_encode(b'hello', alphabet=STANDARD94) == '^)wrPZ'
assert base94_encode(b'\x00abc', alphabet=STANDARD94) == '!(a<R'
| low_context |
21 | devbench-low-context | python | STANDARD91 = ''.join(chr(i) for i in range(33, 124))
REVERSED91 = STANDARD91[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base91_encode(data, alphabet=REVERSED91):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 91)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD91) == 91
# This is integer base-91 with reversed printable alphabet, not basE91.
assert base91_encode(b'abc') == 'sQ</'
assert base91_encode(b'abc') != ')K`m'
assert base91_encode(b'abc', alphabet=STANDARD91) == ')K`m'
assert base91_encode(b'\x00abc') == '{sQ</' | assert base91_encode(b'') == ''
assert base91_encode(b'\x00') == '{'
assert base91_encode('abc') == 'sQ</'
assert base91_encode(b'hello') == '4.MFD:'
assert base91_encode(b'hello', alphabet=STANDARD91) == 'hnOVXb'
assert base91_encode(b'\x00abc', alphabet=STANDARD91) == '!)K`m'
| low_context |
22 | devbench-low-context | python | STANDARD57 = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
REVERSED57 = STANDARD57[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def base57_encode(data, alphabet=REVERSED57):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 57)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(STANDARD57) == 57
# This base57 encoder uses the reversed no-ambiguous-chars alphabet by default.
assert base57_encode(b'abc') == 'QYew'
assert base57_encode(b'abc') != 'cUN5'
assert base57_encode(b'abc', alphabet=STANDARD57) == 'cUN5'
assert base57_encode(b'\x00abc') == 'zQYew' | assert base57_encode(b'') == ''
assert base57_encode(b'\x00') == 'z'
assert base57_encode('abc') == 'QYew'
assert base57_encode(b'hello') == 'mvorsrW'
assert base57_encode(b'hello', alphabet=STANDARD57) == 'F6DA9AW'
assert base57_encode(b'\x00abc', alphabet=STANDARD57) == '2cUN5'
| low_context |
23 | devbench-low-context | python | def clean_and_format(text):
"""Strip whitespace, replace hyphens with spaces, then title-case."""
| stripped = text.strip()
replaced = stripped.replace('-', ' ')
return replaced.title()
|
# Test with leading/trailing whitespace and hyphens
result1 = clean_and_format(' hello-world ')
assert result1 == 'Hello World'
result2 = clean_and_format('foo-bar-baz')
assert result2 == 'Foo Bar Baz'
result3 = clean_and_format(' already clean ')
assert result3 == 'Already Clean'
result4 = clean_and_format('UP... | assert clean_and_format(' hello-world ') == 'Hello World'
assert clean_and_format('foo-bar-baz') == 'Foo Bar Baz'
assert clean_and_format(' already clean ') == 'Already Clean'
assert clean_and_format('UPPER-CASE') == 'Upper Case'
assert clean_and_format('') == ''
| low_context |
24 | devbench-low-context | python | def recursive_power(base, exp):
"""Compute base^exp recursively. exp is a non-negative integer.
Uses the identity: base^0 = 1,
base^exp = base * base^(exp-1) for odd exp,
base^exp = (base^(exp//2))^2 for even exp > 0."""
| if exp == 0:
return 1
if exp % 2 == 1:
return base * recursive_power(base, exp - 1)
half = recursive_power(base, exp // 2)
return half * half
|
# Test basic cases
assert recursive_power(2, 0) == 1
assert recursive_power(2, 1) == 2
assert recursive_power(2, 10) == 1024
assert recursive_power(3, 3) == 27
assert recursive_power(5, 4) == 625
assert recursive_power(0, 0) == 1
assert recursive_power(1, 100) == 1
| assert recursive_power(2, 0) == 1
assert recursive_power(2, 1) == 2
assert recursive_power(2, 10) == 1024
assert recursive_power(3, 3) == 27
assert recursive_power(5, 4) == 625
assert recursive_power(0, 0) == 1
assert recursive_power(0, 5) == 0
assert recursive_power(1, 100) == 1
| low_context |
25 | devbench-low-context | python | def merge_dicts_sum(*dicts):
"""Merge multiple dicts. For duplicate keys, sum the values."""
result = {}
| for d in dicts:
for key, value in d.items():
result[key] = result.get(key, 0) + value
return result
|
# Test merging with conflicts
merged = merge_dicts_sum({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
assert merged == {'a': 1, 'b': 5, 'c': 4}
# Test multiple dicts
merged3 = merge_dicts_sum({'x': 1}, {'x': 2}, {'x': 3})
assert merged3 == {'x': 6}
# Edge cases
assert merge_dicts_sum() == {}
assert merge_dicts_sum({}, {'y': 10... | assert merge_dicts_sum({'a': 1}, {'a': 2}) == {'a': 3}
assert merge_dicts_sum({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) == {'a': 1, 'b': 5, 'c': 4}
assert merge_dicts_sum({}, {'x': 10}) == {'x': 10}
assert merge_dicts_sum() == {}
assert merge_dicts_sum({'a': 1}, {'a': 2}, {'a': 3}) == {'a': 6}
assert merge_dicts_sum({'a': -1... | low_context |
26 | devbench-low-context | python | def split_first_last(items):
"""Return a tuple of (first, middle_list, last).
If len(items) < 2, raise ValueError."""
| if len(items) < 2:
raise ValueError('Need at least 2 items')
first, *middle, last = items
return (first, middle, last)
|
# Test with various sequences
assert split_first_last([1, 2, 3, 4, 5]) == (1, [2, 3, 4], 5)
assert split_first_last([1, 2]) == (1, [], 2)
assert split_first_last('abcde') == ('a', ['b', 'c', 'd'], 'e')
# Test error for short input
try:
split_first_last([1])
assert False, 'Should have raised ValueError'
except... | assert split_first_last([1, 2, 3, 4, 5]) == (1, [2, 3, 4], 5)
assert split_first_last([1, 2]) == (1, [], 2)
assert split_first_last('abcde') == ('a', ['b', 'c', 'd'], 'e')
try:
split_first_last([1])
assert False, 'Should have raised ValueError'
except ValueError:
pass
assert split_first_last(range(1, 6)) ==... | low_context |
27 | devbench-low-context | python | class AppError(Exception):
pass
class ValidationError(AppError):
pass
class DatabaseError(AppError):
pass
def handle_error(error):
"""Return a string identifying which specific handler caught the error.
Most specific exceptions must be caught first."""
try:
raise error
| except ValidationError:
return 'validation'
except DatabaseError:
return 'database'
except AppError:
return 'app'
except Exception:
return 'generic'
| assert handle_error(ValidationError('bad input')) == 'validation'
assert handle_error(DatabaseError('connection failed')) == 'database'
assert handle_error(AppError('general app error')) == 'app'
assert handle_error(RuntimeError('unexpected')) == 'generic'
assert handle_error(ValidationError()) == 'validation'
| low_context | |
28 | devbench-low-context | python | def make_tag(tag, /, content, *, cls=None):
"""Build an HTML tag. `tag` is positional-only,
`content` is normal, `cls` is keyword-only."""
| if cls:
return f'<{tag} class="{cls}">{content}</{tag}>'
return f'<{tag}>{content}</{tag}>'
|
# Basic usage
assert make_tag('p', 'Hello') == '<p>Hello</p>'
assert make_tag('div', 'World', cls='main') == '<div class="main">World</div>'
assert make_tag('span', content='Hi') == '<span>Hi</span>'
# tag must be positional-only
try:
make_tag(tag='p', content='Fail')
assert False, 'tag should be positional-o... | assert make_tag('p', 'Hello') == '<p>Hello</p>'
assert make_tag('div', 'World', cls='main') == '<div class="main">World</div>'
assert make_tag('span', content='Hi') == '<span>Hi</span>'
try:
make_tag(tag='p', content='Fail')
assert False, 'tag should be positional-only'
except TypeError:
pass
try:
make_... | low_context |
29 | devbench-low-context | python | def complex_magnitude(real, imag):
"""Return the magnitude of a complex number."""
| c = complex(real, imag)
magnitude = abs(c)
return magnitude
|
# Test with Pythagorean triple
assert complex_magnitude(3, 4) == 5.0
# Test zero
assert complex_magnitude(0, 0) == 0.0
# Test unit values
assert complex_magnitude(1, 0) == 1.0
assert complex_magnitude(0, 1) == 1.0
# Test irrational result
assert abs(complex_magnitude(1, 1) - 2**0.5) < 1e-9
# Test negative inputs
a... | assert complex_magnitude(3, 4) == 5.0
assert complex_magnitude(0, 0) == 0.0
assert complex_magnitude(1, 0) == 1.0
assert complex_magnitude(0, 1) == 1.0
assert abs(complex_magnitude(1, 1) - 2**0.5) < 1e-9
assert complex_magnitude(-3, -4) == 5.0
| low_context |
30 | devbench-low-context | python | READ = 0b001
WRITE = 0b010
EXECUTE = 0b100
class Permissions:
def __init__(self):
self.flags = 0
def grant(self, perm):
self.flags |= perm
def revoke(self, perm):
self.flags &= ~perm
def toggle(self, perm):
| self.flags ^= perm
def has(self, perm):
return (self.flags & perm) == perm
| p = Permissions()
p.grant(READ)
p.grant(WRITE)
assert p.has(READ)
assert p.has(WRITE)
assert not p.has(EXECUTE)
p.toggle(WRITE)
assert not p.has(WRITE)
p.toggle(WRITE)
assert p.has(WRITE)
p.revoke(READ)
assert not p.has(READ)
assert p.has(WRITE)
p.toggle(EXECUTE)
assert p.has(EXECUTE)
assert p.has(READ | WRITE) == Fals... | low_context | |
31 | devbench-low-context | python | import math
def round_toward_zero(x, ndigits=0):
"""Round x to ndigits decimal places, rounding 0.5 toward zero.
Unlike Python's round() which uses banker's rounding,
this always rounds the 0.5 case toward zero."""
multiplier = 10 ** ndigits
shifted = x * multiplier
| if shifted > 0:
result = math.floor(shifted) if shifted - math.floor(shifted) <= 0.5 else math.ceil(shifted)
else:
result = math.ceil(shifted) if math.ceil(shifted) - shifted <= 0.5 else math.floor(shifted)
return result / multiplier |
# Verify round_toward_zero differs from built-in round for odd .5 values
assert round_toward_zero(3.5) == 3 # round(3.5)==4 in Python (banker's rounds to even)
assert round_toward_zero(0.5) == 0
assert round_toward_zero(-0.5) == 0
| assert round_toward_zero(2.5) == 2
assert round_toward_zero(3.5) == 3
assert round_toward_zero(-2.5) == -2
assert round_toward_zero(-3.5) == -3
assert round_toward_zero(2.6) == 3
assert round_toward_zero(-2.6) == -3
assert round_toward_zero(2.4) == 2
assert round_toward_zero(0.5) == 0
assert round_toward_zero(-0.5) == ... | low_context |
32 | devbench-low-context | python | def zip_with_previous_fill(a, b):
"""Zip two lists; when one is shorter, fill with its last element.
Unlike zip_longest which uses a constant fill, this uses
the last seen element from the shorter list."""
result = []
max_len = max(len(a), len(b))
| for i in range(max_len):
val_a = a[i] if i < len(a) else a[-1]
val_b = b[i] if i < len(b) else b[-1]
result.append((val_a, val_b))
return result |
# Quick smoke test
pairs = zip_with_previous_fill([1, 2, 3], ['a', 'b'])
assert len(pairs) == 3
assert pairs[-1][1] == 'b' # last element of shorter list is reused
| assert zip_with_previous_fill([1, 2, 3], ['a', 'b']) == [(1, 'a'), (2, 'b'), (3, 'b')]
assert zip_with_previous_fill([1], [10, 20, 30]) == [(1, 10), (1, 20), (1, 30)]
assert zip_with_previous_fill([1, 2], [3, 4]) == [(1, 3), (2, 4)]
assert zip_with_previous_fill([5], [9]) == [(5, 9)]
assert zip_with_previous_fill([1, 2... | low_context |
33 | devbench-low-context | python | def repeat_with_sep(s, n, sep='-'):
"""Repeat string s exactly n times, joined by sep.
Example: repeat_with_sep('abc', 3) -> 'abc-abc-abc'
Returns empty string when n <= 0.
Note: This is NOT the same as s * n which gives 'abcabcabc'."""
| if n <= 0:
return ''
return sep.join([s] * n) |
# Smoke tests for repeat_with_sep
result = repeat_with_sep('go', 3, sep='!')
assert result == 'go!go!go'
assert repeat_with_sep('z', 1) == 'z'
assert repeat_with_sep('a', 0) == ''
print('repeat_with_sep basic tests passed')
| assert repeat_with_sep('abc', 3) == 'abc-abc-abc'
assert repeat_with_sep('hi', 1) == 'hi'
assert repeat_with_sep('x', 4, sep=', ') == 'x, x, x, x'
assert repeat_with_sep('ab', 0) == ''
assert repeat_with_sep('test', 2, sep='|') == 'test|test' | low_context |
34 | devbench-low-context | python | import math
def c_style_div(a, b):
"""Integer division that truncates toward zero (C/Java style).
Python's // operator floors toward negative infinity, but C/Java
truncate toward zero. Implement the C/Java behavior."""
| if b == 0:
raise ZeroDivisionError('division by zero')
return int(a / b) |
def c_style_mod(a, b):
"""C-style modulo consistent with c_style_div.
Satisfies: a == b * c_style_div(a, b) + c_style_mod(a, b)"""
return a - b * c_style_div(a, b)
# Verify div and mod are consistent
assert c_style_div(7, 2) * 2 + c_style_mod(7, 2) == 7
assert c_style_div(-7, 2) * 2 + c_style_mod(-7, 2) ... | assert c_style_div(7, 2) == 3
assert c_style_div(-7, 2) == -3
assert c_style_div(7, -2) == -3
assert c_style_div(-7, -2) == 3
assert c_style_div(0, 5) == 0
assert c_style_div(10, 3) == 3
assert c_style_div(-10, 3) == -3
assert c_style_div(1, 2) == 0
assert c_style_div(-1, 2) == 0 | low_context |
35 | devbench-low-context | python | def matches_char_class(char, pattern):
"""Check if char matches a bracket pattern like 'a-z', 'A-Z0-9', 'aeiou'.
Supports ranges (e.g., 'a-z') and literal characters.
No regex module used."""
i = 0
while i < len(pattern):
| if i + 2 < len(pattern) and pattern[i + 1] == '-':
if pattern[i] <= char <= pattern[i + 2]: return True
i += 3
else:
if char == pattern[i]: return True
i += 1
return False |
# Quick verification
assert matches_char_class('c', 'a-z')
assert not matches_char_class('C', 'a-z')
assert matches_char_class('5', '0-9')
| assert matches_char_class('m', 'a-z') == True
assert matches_char_class('M', 'a-z') == False
assert matches_char_class('5', '0-9') == True
assert matches_char_class('a', '0-9') == False
assert matches_char_class('e', 'aeiou') == True
assert matches_char_class('b', 'aeiou') == False
assert matches_char_class('Z', 'A-Za-... | low_context |
36 | devbench-low-context | python | class CountedProperty:
"""A descriptor that counts how many times the attribute is accessed.
Stores the count on the instance, not the descriptor."""
def __init__(self, func):
self.func = func
self.attr_name = func.__name__
self.count_attr = '_access_count_' + func.__name__
| def __get__(self, obj, objtype=None):
if obj is None:
return self
if not hasattr(obj, self.count_attr):
setattr(obj, self.count_attr, 0)
setattr(obj, self.count_attr, getattr(obj, self.count_attr) + 1)
return self.func(obj) |
class MyObj:
def __init__(self, val):
self._val = val
@CountedProperty
def value(self):
return self._val
| o = MyObj(42)
assert o.value == 42
assert o.value == 42
assert o.value == 42
assert o._access_count_value == 3
o2 = MyObj(10)
assert o2.value == 10
assert o2._access_count_value == 1
assert o._access_count_value == 3 | low_context |
37 | devbench-low-context | python | def shallow_equal(a, b):
"""Check if two dicts have the same set of keys (ignore values).
Two dicts are shallow-equal if they have identical key sets,
regardless of what values those keys map to."""
| keys_a = set(a.keys())
keys_b = set(b.keys())
return keys_a == keys_b |
def deep_equal(a, b):
"""Full dict equality: same keys AND same values."""
return a == b
# Demonstrate the difference between shallow and deep equality
d1 = {'x': 1, 'y': 2}
d2 = {'x': 99, 'y': 0}
assert shallow_equal(d1, d2) == True # same keys
assert deep_equal(d1, d2) == False # different values
pr... | assert shallow_equal({'x': 1, 'y': 2}, {'x': 99, 'y': 0}) == True
assert shallow_equal({'x': 1}, {'x': 1, 'y': 2}) == False
assert shallow_equal({}, {}) == True
assert shallow_equal({'a': 1, 'b': 2, 'c': 3}, {'c': 0, 'b': 0, 'a': 0}) == True
assert shallow_equal({'a': 1}, {}) == False | low_context |
38 | devbench-low-context | python | def interleave(s1, s2):
"""Interleave two strings character by character.
When strings differ in length, append remaining
characters of the longer string at the end."""
result = []
min_len = min(len(s1), len(s2))
| for i in range(min_len):
result.append(s1[i])
result.append(s2[i])
result.append(s1[min_len:])
result.append(s2[min_len:])
return ''.join(result) |
# Quick check
assert interleave('ab', 'cd') == 'acbd'
assert interleave('a', '123') == 'a123'
print('interleave smoke tests passed')
| assert interleave('abc', '123') == 'a1b2c3'
assert interleave('ab', '1234') == 'a1b234'
assert interleave('abcd', '12') == 'a1b2cd'
assert interleave('', 'xyz') == 'xyz'
assert interleave('hello', '') == 'hello'
assert interleave('', '') == ''
assert interleave('a', 'b') == 'ab' | low_context |
39 | devbench-low-context | python | class TruthyDict(dict):
"""A dict subclass where bool() is always True,
even when the dict is empty. Opposite of Python default
where bool({}) is False."""
| def __bool__(self):
return True
def is_none(self):
return False |
class NoneDict(TruthyDict):
"""Represents a None/null dict value."""
def __bool__(self):
return False
def is_none(self):
return True
| d = TruthyDict()
assert bool(d) == True
assert len(d) == 0
d2 = TruthyDict({'a': 1})
assert bool(d2) == True
nd = NoneDict()
assert bool(nd) == False
assert nd.is_none() == True
assert d.is_none() == False | low_context |
40 | devbench-low-context | python | from itertools import zip_longest
def transpose_jagged(matrix, fill=None):
"""Transpose a potentially jagged 2D list.
Unlike zip(*matrix) which drops elements from longer rows,
this fills missing values with fill parameter."""
| if not matrix:
return []
return [list(row) for row in zip_longest(*matrix, fillvalue=fill)] |
# Quick smoke test
result = transpose_jagged([[1, 2], [3]])
assert result == [[1, 3], [2, None]]
assert transpose_jagged([]) == []
print('transpose_jagged basic tests passed')
| assert transpose_jagged([[1, 2, 3], [4, 5], [6]]) == [[1, 4, 6], [2, 5, None], [3, None, None]]
assert transpose_jagged([[1, 2], [3, 4]]) == [[1, 3], [2, 4]]
assert transpose_jagged([]) == []
assert transpose_jagged([[1]]) == [[1]]
assert transpose_jagged([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 4, 7], [2, 5, 8], [3,... | low_context |
41 | devbench-low-context | python | Z85 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#'
REVZ85 = Z85[::-1]
def leading_zero_bytes(data):
i = 0
for b in data:
if b != 0:
return i
i += 1
return i
| def z85_encode(data, alphabet=REVZ85):
data = data.encode() if isinstance(data, str) else data
n = int.from_bytes(data, 'big')
out = []
while n:
n, r = divmod(n, 85)
out.append(alphabet[r])
return alphabet[0] * leading_zero_bytes(data) + ''.join(reversed(out))
| assert len(Z85) == 85
# This is integer-style z85 with a reversed default alphabet, not fixed-width ZeroMQ Z85.
assert z85_encode(b'abcd') == 'RXMmu'
assert z85_encode(b'abcd') != 'vpA.S'
assert z85_encode(b'abcd', alphabet=Z85) == 'vpA.S'
assert z85_encode(b'\x00abc') == '#>PTJ' | assert z85_encode(b'') == ''
assert z85_encode(b'\x00') == '#'
assert z85_encode('abc') == '>PTJ'
assert z85_encode(b'hello') == '$!}E$9.'
assert z85_encode(b'hello', alphabet=Z85) == '1g4I1(m'
assert z85_encode(b'\x00abc', alphabet=Z85) == '0axtD'
| low_context |
42 | devbench-low-context | python | import functools
def fallback_to_args(func):
"""Decorator: if func returns None, return the args tuple instead.
If func has a single arg, return that arg directly (not a 1-tuple)."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
| result = func(*args, **kwargs)
if result is None:
return args[0] if len(args) == 1 else args
return result |
return wrapper
@fallback_to_args
def maybe_process(x):
if x > 0:
return x * 2
return None
# When result is not None, return the result
assert maybe_process(5) == 10
# When result is None with single arg, return arg directly
assert maybe_process(-3) == -3
| assert maybe_process(5) == 10
assert maybe_process(-3) == -3
assert maybe_process(0) == 0
@fallback_to_args
def multi_arg(a, b):
return None
assert multi_arg(1, 2) == (1, 2)
@fallback_to_args
def returns_value(x):
return 'ok'
assert returns_value(99) == 'ok'
| low_context |
43 | devbench-low-context | python | import re
def reverse_format(template, *args):
"""Like str.format but {0} refers to the LAST argument,
{1} to the second-to-last, and so on (reversed indexing)."""
| reversed_args = args[::-1]
return template.format(*reversed_args) |
# Usage examples
result = reverse_format('{0} {1} {2}', 'a', 'b', 'c')
assert result == 'c b a'
# Single arg: {0} refers to the only (and last) arg
assert reverse_format('{0}', 'only') == 'only'
# Repeated reference
assert reverse_format('{0}{0}', 'x', 'y') == 'yy'
| assert reverse_format('{0} {1} {2}', 'a', 'b', 'c') == 'c b a'
assert reverse_format('{0}', 'only') == 'only'
assert reverse_format('{0}-{1}', 'first', 'second') == 'second-first'
assert reverse_format('no placeholders') == 'no placeholders'
assert reverse_format('{0}{0}', 'x', 'y') == 'yy'
| low_context |
44 | devbench-low-context | python | class FuzzyString:
"""String wrapper where 'in' checks are case-insensitive
and ignore all whitespace in both operands."""
def __init__(self, text):
self.text = text
def __repr__(self):
return f'FuzzyString({self.text!r})'
def __contains__(self, item):
| normalized = self.text.lower().replace(' ', '')
item_normalized = item.lower().replace(' ', '')
return item_normalized in normalized |
s = FuzzyString('Hello World')
assert 'hello' in s
assert 'WORLD' in s
assert 'helloworld' in s
assert 'xyz' not in s
| s = FuzzyString('Hello World')
assert 'hello' in s
assert 'WORLD' in s
assert 'helloworld' in s
assert 'lo wo' in s
assert 'HELLO WORLD' in s
assert 'xyz' not in s
assert '' in s
assert 'h e l l o' in s
| low_context |
45 | devbench-low-context | python | class ThresholdAccumulator:
"""Accumulates values. When the total reaches or exceeds
the threshold, subtract threshold (possibly multiple times)
and increment overflow_count for each subtraction."""
def __init__(self, threshold):
self.threshold = threshold
self.total = 0
self.ove... | self.total += value
while self.total >= self.threshold:
self.total -= self.threshold
self.overflow_count += 1 |
acc = ThresholdAccumulator(10)
acc.add(4)
assert acc.total == 4 and acc.overflow_count == 0
acc.add(6)
assert acc.total == 0 and acc.overflow_count == 1
| acc = ThresholdAccumulator(10)
acc.add(4)
assert acc.total == 4 and acc.overflow_count == 0
acc.add(6)
assert acc.total == 0 and acc.overflow_count == 1
acc.add(25)
assert acc.total == 5 and acc.overflow_count == 3
acc.add(5)
assert acc.total == 0 and acc.overflow_count == 4
| low_context |
46 | devbench-low-context | python | def skip_every_n(iterable, n):
"""Yield all elements EXCEPT every Nth one.
The Nth element is 1-indexed (skip positions n, 2n, 3n, ...).
For example, skip_every_n([1,2,3,4,5,6], 2) yields 1,3,5."""
| for i, item in enumerate(iterable, 1):
if i % n != 0:
yield item |
# Test: skip every 3rd from 1..10
result = list(skip_every_n(range(1, 11), 3))
assert result == [1, 2, 4, 5, 7, 8, 10]
# Skip every 2nd
assert list(skip_every_n([10, 20, 30, 40], 2)) == [10, 30]
# Edge: n=1 skips everything
assert list(skip_every_n('abcdef', 1)) == []
| assert list(skip_every_n(range(1, 11), 3)) == [1, 2, 4, 5, 7, 8, 10]
assert list(skip_every_n([10, 20, 30, 40], 2)) == [10, 30]
assert list(skip_every_n([], 5)) == []
assert list(skip_every_n('abcdef', 1)) == []
assert list(skip_every_n([1, 2, 3], 100)) == [1, 2, 3]
| low_context |
47 | devbench-low-context | python | def safe_merge(base, updates):
"""Merge updates into base, but ONLY add new keys.
Existing keys in base keep their original values.
Returns the modified base dict (in-place mutation)."""
| for key, value in updates.items():
if key not in base:
base[key] = value
return base |
d = {'a': 1, 'b': 2}
result = safe_merge(d, {'b': 99, 'c': 3})
# 'b' keeps original value 2, 'c' is added
assert result == {'a': 1, 'b': 2, 'c': 3}
# Must modify in-place, not create new dict
assert result is d
assert safe_merge({}, {'x': 1}) == {'x': 1}
| d = {'a': 1, 'b': 2}
result = safe_merge(d, {'b': 99, 'c': 3})
assert result == {'a': 1, 'b': 2, 'c': 3}
assert result is d
assert safe_merge({}, {'x': 1}) == {'x': 1}
assert safe_merge({'x': 1}, {}) == {'x': 1}
assert safe_merge({'a': 0}, {'a': 100, 'b': 200}) == {'a': 0, 'b': 200}
| low_context |
48 | devbench-low-context | python | def inclusive_range(start, stop, step=1):
"""Like range() but includes BOTH endpoints.
Works for positive step only."""
| result = []
current = start
while current <= stop:
result.append(current)
current += step
return result |
# Both endpoints are included
assert inclusive_range(1, 5) == [1, 2, 3, 4, 5]
# Single element when start == stop
assert inclusive_range(0, 0) == [0]
# Step > 1
assert inclusive_range(0, 6, 2) == [0, 2, 4, 6]
# Stop not exactly on step boundary
assert inclusive_range(2, 10, 3) == [2, 5, 8]
| assert inclusive_range(1, 5) == [1, 2, 3, 4, 5]
assert inclusive_range(0, 0) == [0]
assert inclusive_range(2, 10, 3) == [2, 5, 8]
assert inclusive_range(1, 1) == [1]
assert inclusive_range(0, 6, 2) == [0, 2, 4, 6]
| low_context |
49 | devbench-low-context | python | def anti_stable_sort(items, key=None):
"""Sort items, but equal elements appear in REVERSE order
of their original positions (anti-stable).
If key is None, compare items directly."""
| decorated = list(enumerate(items))
keyfunc = key if key else lambda x: x
decorated.sort(key=lambda pair: (keyfunc(pair[1]), -pair[0]))
return [item for _, item in decorated] |
# Tuples sorted by first element; equal firsts are reversed
data = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd')]
result = anti_stable_sort(data, key=lambda x: x[0])
assert result == [(1, 'c'), (1, 'a'), (2, 'd'), (2, 'b')]
# Already-distinct elements sort normally
assert anti_stable_sort([3, 1, 2]) == [1, 2, 3]
assert an... | data = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd')]
result = anti_stable_sort(data, key=lambda x: x[0])
assert result == [(1, 'c'), (1, 'a'), (2, 'd'), (2, 'b')]
assert anti_stable_sort([3, 1, 2]) == [1, 2, 3]
assert anti_stable_sort([]) == []
assert anti_stable_sort([5, 5, 5]) == [5, 5, 5]
r = anti_stable_sort([3, 1, 3,... | low_context |
50 | devbench-low-context | python | def make_multipliers(n):
"""Return a list of n functions where the i-th function
multiplies its argument by i (0-indexed).
Must use default argument capture to avoid the closure gotcha."""
| return [lambda x, i=i: x * i for i in range(n)] |
fns = make_multipliers(5)
# Each function should multiply by its index
assert fns[0](10) == 0 # 10 * 0
assert fns[1](10) == 10 # 10 * 1
assert fns[2](10) == 20 # 10 * 2
assert fns[3](10) == 30 # 10 * 3
assert fns[4](10) == 40 # 10 * 4
# Different input
assert fns[2](5) == 10 # 5 * 2
| fns = make_multipliers(5)
assert fns[0](10) == 0
assert fns[1](10) == 10
assert fns[2](10) == 20
assert fns[3](10) == 30
assert fns[4](10) == 40
assert fns[2](5) == 10
assert len(make_multipliers(0)) == 0
assert make_multipliers(1)[0](7) == 0
| low_context |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.