Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write is_leap(year: int) -> bool to return whether year is a leap year in the Gregorian calendar.
def is_leap(year: int) -> bool:
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write is_leap(year: int) -> bool to return whether year is a leap year in the Gregorian calendar.
def is_leap(year: int) -> bool:
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write is_leap(year: int) -> bool to return whether year is a leap year in the Gregorian calendar.
def is_leap(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
def rle(s: str) -> str:
if not s:
return ""
result = []
current = s[0]
count = 1
for ch in s[1:]:
if ch == current:
count += 1
else:
result.append(f"{current}{count}")
current = ch
count = 1
result.append(f"{current}{count}")
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
import itertools
def rle(s: str) -> str:
return "".join(f"{char}{len(list(group))}" for char, group in itertools.groupby(s))
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
def rle(s: str) -> str:
if not s:
return ""
result = []
current = s[0]
count = 1
for ch in s[1:]:
if ch == current:
count += 1
else:
result.append(current)
result.append(str(count))
current = ch
count = 1
result.append(current)
result.append(str(count))
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
import itertools
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
iterator = iter(items)
result = []
while True:
chunk = list(itertools.islice(iterator, n))
if not chunk:
break
result.append(chunk)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
result = []
current = []
for item in items:
current.append(item)
if len(current) == n:
result.append(current)
current = []
if current:
result.append(current)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
result: list[list] = []
current: list = []
for item in items:
current.append(item)
if len(current) == n:
result.append(current)
current = []
if current:
result.append(current)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP, localcontext
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
try:
adjusted = d.adjusted()
except Exception:
adjusted = 0
if d == 0:
adjusted = 0
precision = max(28, adjusted + digits + 3)
if precision < 1:
precision = 1
quantum = Decimal("1e{}".format(-digits))
with localcontext() as ctx:
ctx.prec = precision
emax = max(999999, abs(adjusted) + abs(digits) + 10)
ctx.Emax = emax
ctx.Emin = -emax
rounded = d.quantize(quantum, rounding=ROUND_HALF_UP)
return format(rounded, "f")
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, localcontext, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
if d.is_finite():
prec = max(
28,
len(d.as_tuple().digits) + 5,
d.adjusted() + digits + 2,
digits + 1,
)
else:
prec = 28
with localcontext() as ctx:
ctx.prec = prec
ctx.rounding = ROUND_HALF_UP
unit = Decimal(1).scaleb(-digits)
rounded = d.quantize(unit, rounding=ROUND_HALF_UP)
return str(rounded)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP, localcontext
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
quantizer = Decimal(1).scaleb(-digits)
with localcontext() as ctx:
ctx.prec = max(28, len(d.as_tuple().digits) + abs(d.as_tuple().exponent) + digits + 10)
rounded = d.quantize(quantizer, rounding=ROUND_HALF_UP)
return format(rounded, "f")
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
def parse_kv(line: str) -> dict[str, str]:
result: dict[str, str] = {}
n = len(line)
i = 0
while i < n and line[i].isspace():
i += 1
while i < n:
start = i
while i < n and not line[i].isspace() and line[i] != "=":
i += 1
key = line[start:i]
if i < n and line[i] == "=":
i += 1
else:
while i < n and not line[i].isspace():
i += 1
while i < n and line[i].isspace():
i += 1
continue
if i < n and line[i] == '"':
i += 1
start = i
while i < n and line[i] != '"':
i += 1
value = line[start:i]
if i < n and line[i] == '"':
i += 1
else:
start = i
while i < n and not line[i].isspace():
i += 1
value = line[start:i]
result[key] = value
while i < n and line[i].isspace():
i += 1
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
def parse_kv(line: str) -> dict[str, str]:
result: dict[str, str] = {}
i = 0
n = len(line)
while i < n and line[i].isspace():
i += 1
while i < n:
key_start = i
while i < n and line[i] != "=" and not line[i].isspace():
i += 1
key = line[key_start:i]
while i < n and line[i].isspace():
i += 1
if i >= n or line[i] != "=":
break
i += 1 # skip '='
if i < n and line[i] == '"':
i += 1
value_start = i
while i < n and line[i] != '"':
i += 1
value = line[value_start:i]
if i < n and line[i] == '"':
i += 1
else:
value_start = i
while i < n and not line[i].isspace():
i += 1
value = line[value_start:i]
result[key] = value
while i < n and line[i].isspace():
i += 1
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
def parse_kv(line: str) -> dict[str, str]:
result: dict[str, str] = {}
i = 0
n = len(line)
while i < n and line[i].isspace():
i += 1
while i < n:
key_start = i
while i < n and line[i] != '=' and not line[i].isspace():
i += 1
if i >= n or line[i] != '=':
break
key = line[key_start:i]
i += 1 # skip '='
if i < n and line[i] == '"':
i += 1
value_start = i
while i < n and line[i] != '"':
i += 1
value = line[value_start:i]
if i < n and line[i] == '"':
i += 1
else:
value_start = i
while i < n and not line[i].isspace():
i += 1
value = line[value_start:i]
if key:
result[key] = value
while i < n and line[i].isspace():
i += 1
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]. The input intervals may be in any order. Merge intervals that overlap or touch, so (1, 2) and (2, 3) become (1, 3). Return the merged intervals as tuples sorted by start, and leave the input list unchanged.
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
ordered = sorted(intervals, key=lambda interval: interval[0])
merged = [ordered[0]]
for start, end in ordered[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, max(last_end, end))
else:
merged.append((start, end))
return merged
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]. The input intervals may be in any order. Merge intervals that overlap or touch, so (1, 2) and (2, 3) become (1, 3). Return the merged intervals as tuples sorted by start, and leave the input list unchanged.
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
sorted_intervals = sorted(intervals)
merged: list[tuple[int, int]] = [sorted_intervals[0]]
for start, end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
if end > last_end:
merged[-1] = (last_start, end)
else:
merged.append((start, end))
return merged
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]. The input intervals may be in any order. Merge intervals that overlap or touch, so (1, 2) and (2, 3) become (1, 3). Return the merged intervals as tuples sorted by start, and leave the input list unchanged.
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
sorted_intervals = sorted(intervals)
merged = [sorted_intervals[0]]
for start, end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, max(last_end, end))
else:
merged.append((start, end))
return merged
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write add_months(d: datetime.date, months: int) -> datetime.date to add months calendar months to d. months may be negative. If the day does not exist in the target month, use the last day of that month.
import calendar
import datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.year * 12 + (d.month - 1) + months
year, month_index = divmod(total_months, 12)
month = month_index + 1
last_day = calendar.monthrange(year, month)[1]
day = min(d.day, last_day)
return datetime.date(year, month, day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write add_months(d: datetime.date, months: int) -> datetime.date to add months calendar months to d. months may be negative. If the day does not exist in the target month, use the last day of that month.
import calendar
import datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.year * 12 + d.month - 1 + months
year, month_index = divmod(total_months, 12)
month = month_index + 1
day = min(d.day, calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write add_months(d: datetime.date, months: int) -> datetime.date to add months calendar months to d. months may be negative. If the day does not exist in the target month, use the last day of that month.
import calendar
import datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.year * 12 + (d.month - 1) + months
year, month_index = divmod(total_months, 12)
month = month_index + 1
last_day = calendar.monthrange(year, month)[1]
day = min(d.day, last_day)
return datetime.date(year, month, day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
import re
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
if k <= 0:
return []
counts = Counter(match.lower() for match in re.findall(r"[A-Za-z']+", text))
return sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
import re
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(word.lower() for word in words)
ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
if k <= 0:
return []
return ordered[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
import re
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(word.lower() for word in words)
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return ranked[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write flatten(obj: dict, sep: str = ".") -> dict. Flatten nested dicts and lists into a single level, joining keys with sep and using list indices as keys. Keep an empty dict or empty list as the value at its key. flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result: dict = {}
def visit(value, prefix):
if isinstance(value, dict):
if not value:
if prefix is not None:
result[prefix] = {}
return
for key, item in value.items():
key_str = str(key)
next_prefix = key_str if prefix is None else f"{prefix}{sep}{key_str}"
visit(item, next_prefix)
elif isinstance(value, list):
if not value:
if prefix is not None:
result[prefix] = []
return
for index, item in enumerate(value):
next_prefix = str(index) if prefix is None else f"{prefix}{sep}{index}"
visit(item, next_prefix)
else:
if prefix is not None:
result[prefix] = value
visit(obj, None)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write flatten(obj: dict, sep: str = ".") -> dict. Flatten nested dicts and lists into a single level, joining keys with sep and using list indices as keys. Keep an empty dict or empty list as the value at its key. flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def walk(value, prefix):
if isinstance(value, dict):
if not value:
if prefix is not None:
result[prefix] = {}
return
for key, item in value.items():
next_prefix = str(key) if prefix is None else f"{prefix}{sep}{key}"
walk(item, next_prefix)
elif isinstance(value, list):
if not value:
if prefix is not None:
result[prefix] = []
return
for index, item in enumerate(value):
next_prefix = str(index) if prefix is None else f"{prefix}{sep}{index}"
walk(item, next_prefix)
else:
if prefix is not None:
result[prefix] = value
walk(obj, None)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write flatten(obj: dict, sep: str = ".") -> dict. Flatten nested dicts and lists into a single level, joining keys with sep and using list indices as keys. Keep an empty dict or empty list as the value at its key. flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def visit(value, prefix: str) -> None:
if isinstance(value, dict):
if not value:
if prefix:
result[prefix] = {}
return
for key, item in value.items():
child_prefix = str(key) if not prefix else f"{prefix}{sep}{key}"
visit(item, child_prefix)
elif isinstance(value, list):
if not value:
if prefix:
result[prefix] = []
return
for index, item in enumerate(value):
child_prefix = (
str(index) if not prefix else f"{prefix}{sep}{index}"
)
visit(item, child_prefix)
else:
if prefix:
result[prefix] = value
visit(obj, "")
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
def lru(maxsize: int):
def decorator(func):
cache = {}
def wrapper(*args, **kwargs):
key = args
if kwargs:
key = args + (tuple(sorted(kwargs.items())),)
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
if maxsize is not None:
while len(cache) > maxsize:
cache.popitem(last=False)
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
def lru(maxsize):
def decorator(func):
cache = {}
def wrapper(*args):
if args in cache:
value = cache.pop(args)
cache[args] = value
return value
result = func(*args)
if maxsize is None or maxsize > 0:
if maxsize is not None and len(cache) >= maxsize:
del cache[next(iter(cache))]
cache[args] = result
return result
wrapper.__name__ = getattr(func, "__name__", wrapper.__name__)
wrapper.__qualname__ = getattr(func, "__qualname__", wrapper.__qualname__)
wrapper.__doc__ = func.__doc__
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
from collections import OrderedDict
from functools import wraps
def lru(maxsize):
def decorator(func):
cache = OrderedDict()
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
if maxsize is None or maxsize > 0:
if maxsize is not None and len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = result
return result
return wrapper
return decorator