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 "".
from itertools import groupby
def rle(s: str) -> str:
return "".join(f"{char}{sum(1 for _ in group)}" for char, group in 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 "".
from itertools import groupby
def rle(s: str) -> str:
return "".join(f"{char}{sum(1 for _ in group)}" for char, group in 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 "".
from itertools import groupby
def rle(s: str) -> str:
return "".join(f"{char}{sum(1 for _ in group)}" for char, group in 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 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.
from itertools import batched
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(batch) for batch in batched(items, n)]
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.
from itertools import batched
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(batch) for batch in batched(items, n)]
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.
from itertools import batched
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(batch) for batch in batched(items, n)]
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)
with localcontext() as ctx:
ctx.prec = max(28, d.adjusted() + digits + 10)
target = Decimal(f"1e-{digits}")
res = d.quantize(target, rounding=ROUND_HALF_UP)
if res.is_zero():
res = res.copy_abs()
return f"{res: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, ROUND_HALF_UP, localcontext
def round_half_up(value: str, digits: int) -> str:
with localcontext() as ctx:
ctx.prec = max(28, len(value) + abs(digits) + 14)
d = Decimal(value)
target = Decimal("10") ** -digits
res = d.quantize(target, rounding=ROUND_HALF_UP)
if res == 0:
res = abs(res)
return f"{res: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, ROUND_HALF_UP, localcontext
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
int_digits = max(1, len(d.as_tuple().digits) + d.as_tuple().exponent)
prec = max(28, int_digits + digits + 10)
with localcontext() as ctx:
ctx.prec = prec
target = Decimal("1") if digits == 0 else Decimal(f"1e-{digits}")
result = d.quantize(target, rounding=ROUND_HALF_UP)
if result == 0:
result = result.copy_abs()
return f"{result: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.
import re
def parse_kv(line: str) -> dict[str, str]:
result: dict[str, str] = {}
for match in re.finditer(r'([^\s=]+)=(?:"([^"]*)"|(\S*))', line):
key = match.group(1)
val = match.group(2) if match.group(2) is not None else match.group(3)
result[key] = val
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.
import re
def parse_kv(line: str) -> dict[str, str]:
result = {}
pattern = re.compile(r'([^\s=]+)=(?:"([^"]*)"|([^\s]*))')
for match in pattern.finditer(line):
k, qv, uqv = match.groups()
result[k] = qv if qv is not None else uqv
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.
import re
def parse_kv(line: str) -> dict[str, str]:
pattern = re.compile(r'([^=\s]+)=(?:"([^"]*)"|(\S*))')
result = {}
for match in pattern.finditer(line):
key = match.group(1)
value = match.group(2) if match.group(2) is not None else match.group(3)
result[key] = value
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 []
sorted_intervals = sorted(intervals)
merged: list[tuple[int, int]] = [sorted_intervals[0]]
for start, end in sorted_intervals[1:]:
prev_start, prev_end = merged[-1]
if start <= prev_end:
merged[-1] = (prev_start, max(prev_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:
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]]:
merged: list[tuple[int, int]] = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], 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:
month_idx = d.month - 1 + months
year = d.year + month_idx // 12
month = month_idx % 12 + 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:
month_index = d.month - 1 + months
new_year = d.year + month_index // 12
new_month = month_index % 12 + 1
max_days = calendar.monthrange(new_year, new_month)[1]
new_day = min(d.day, max_days)
return datetime.date(new_year, new_month, new_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 = total_months // 12
month = total_months % 12 + 1
max_day = calendar.monthrange(year, month)[1]
return datetime.date(year, month, min(d.day, max_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.
from collections import Counter
import re
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = [w.lower() for w in re.findall(r"[A-Za-z']+", text)]
counts = Counter(words)
return sorted(counts.items(), key=lambda item: (-item[1], item[0]))[
: max(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.
from collections import Counter
import re
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
if k <= 0:
return []
words = (w.lower() for w in re.findall(r"[A-Za-z']+", text))
counts = Counter(words)
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.
from collections import Counter
import re
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zA-Z']+", text.lower())
counts = Counter(words)
sorted_words = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return sorted_words[: max(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 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 _flatten(curr, prefix=None):
if isinstance(curr, dict):
if not curr and prefix is not None:
result[prefix] = curr
else:
for k, v in curr.items():
new_key = f"{prefix}{sep}{k}" if prefix is not None else str(k)
_flatten(v, new_key)
elif isinstance(curr, list):
if not curr and prefix is not None:
result[prefix] = curr
else:
for i, v in enumerate(curr):
new_key = f"{prefix}{sep}{i}" if prefix is not None else str(i)
_flatten(v, new_key)
else:
result[prefix] = curr
_flatten(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 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 _flatten(current, prefix):
if isinstance(current, dict):
if not current and prefix != "":
result[prefix] = current
else:
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
_flatten(v, new_key)
elif isinstance(current, list):
if not current and prefix != "":
result[prefix] = current
else:
for idx, v in enumerate(current):
new_key = f"{prefix}{sep}{idx}" if prefix else str(idx)
_flatten(v, new_key)
else:
result[prefix] = current
_flatten(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 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 _flatten(current, prefix):
if isinstance(current, dict):
if not current and prefix:
result[prefix] = {}
else:
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
_flatten(v, new_key)
elif isinstance(current, list):
if not current:
result[prefix] = []
else:
for i, v in enumerate(current):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
_flatten(v, new_key)
else:
result[prefix] = current
_flatten(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__.
from collections import OrderedDict
from functools import wraps
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
@wraps(func)
def wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
if maxsize > 0:
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = result
return result
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: int):
def decorator(func):
cache = OrderedDict()
@wraps(func)
def wrapper(*args):
if args in cache:
cache.move_to_end(args)
return cache[args]
result = func(*args)
if maxsize > 0:
cache[args] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
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: int):
def decorator(fn):
cache = OrderedDict()
@wraps(fn)
def wrapper(*args):
if maxsize <= 0:
return fn(*args)
if args in cache:
cache.move_to_end(args)
return cache[args]
result = fn(*args)
cache[args] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
return wrapper
return decorator