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(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 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 ""
parts = []
current = s[0]
count = 1
for ch in s[1:]:
if ch == current:
count += 1
else:
parts.append(current)
parts.append(str(count))
current = ch
count = 1
parts.append(current)
parts.append(str(count))
return "".join(parts)
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.
from itertools import islice
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
iterator = iter(items)
result: list[list] = []
while True:
batch = list(islice(iterator, n))
if not batch:
break
result.append(batch)
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")
iterator = iter(items)
result: list[list] = []
while True:
chunk: list = []
for _ in range(n):
try:
chunk.append(next(iterator))
except StopIteration:
break
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: 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, localcontext, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
with localcontext() as ctx:
d = Decimal(value)
t = d.as_tuple()
ctx.prec = max(28, len(t.digits) + abs(t.exponent) + abs(digits) + 10)
quantum = Decimal(1).scaleb(-digits)
rounded = d.quantize(quantum, rounding=ROUND_HALF_UP)
if rounded == 0:
rounded = rounded.copy_abs()
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, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
quant = Decimal(10) ** -digits
return format(Decimal(value).quantize(quant, rounding=ROUND_HALF_UP), "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:
if digits < 0:
raise ValueError("digits must be non-negative")
quant = Decimal(10) ** (-digits)
with localcontext() as ctx:
ctx.prec = max(28, len(value) + digits + 10)
result = Decimal(value).quantize(quant, rounding=ROUND_HALF_UP)
if result == 0:
result = Decimal(0).quantize(quant)
return format(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.
def parse_kv(line: str) -> dict[str, str]:
result: dict[str, str] = {}
i = 0
n = len(line)
while i < n:
while i < n and line[i] == ' ':
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] not in (' ', '='):
i += 1
key = line[key_start:i]
while i < n and line[i] == ' ':
i += 1
if i >= n or line[i] != '=':
continue
i += 1
if i < n and line[i] == '"':
i += 1
val_start = i
while i < n and line[i] != '"':
i += 1
value = line[val_start:i]
if i < n and line[i] == '"':
i += 1
else:
val_start = i
while i < n and line[i] != ' ':
i += 1
value = line[val_start:i]
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 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:
while i < n and line[i] == ' ':
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=' and line[i] != ' ':
i += 1
key = line[key_start:i]
if i >= n or line[i] != '=':
continue
i += 1
if i < n and line[i] == '"':
i += 1
chars: list[str] = []
while i < n and line[i] != '"':
chars.append(line[i])
i += 1
if i < n and line[i] == '"':
i += 1
value = ''.join(chars)
else:
start = i
while i < n and line[i] != ' ':
i += 1
value = line[start:i]
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 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:
while i < n and line[i] == ' ':
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=' and line[i] != ' ':
i += 1
key = line[key_start:i]
if i >= n or line[i] != '=':
while i < n and line[i] != ' ':
i += 1
continue
i += 1
if i < n and line[i] == '"':
i += 1
val_start = i
while i < n and line[i] != '"':
i += 1
value = line[val_start:i]
if i < n and line[i] == '"':
i += 1
else:
val_start = i
while i < n and line[i] != ' ':
i += 1
value = line[val_start:i]
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, key=lambda iv: (iv[0], iv[1]))
merged: list[tuple[int, int]] = []
for start, end in sorted_intervals:
if merged and start <= merged[-1][1]:
prev_start, prev_end = merged[-1]
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, key=lambda iv: (iv[0], iv[1]))
merged: list[tuple[int, int]] = []
cur_start, cur_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= cur_end:
cur_end = max(cur_end, end)
else:
merged.append((cur_start, cur_end))
cur_start, cur_end = start, end
merged.append((cur_start, cur_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, key=lambda interval: (interval[0], interval[1]))
merged: list[tuple[int, int]] = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end:
current_end = max(current_end, end)
else:
merged.append((current_start, current_end))
current_start, current_end = start, end
merged.append((current_start, current_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 = d.year * 12 + (d.month - 1) + months
year, month0 = divmod(total, 12)
month = month0 + 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 datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.year * 12 + (d.month - 1) + months
new_year, new_month_zero_based = divmod(total_months, 12)
new_month = new_month_zero_based + 1
if new_month == 12:
next_year = new_year + 1
next_month = 1
else:
next_year = new_year
next_month = new_month + 1
last_day = (
datetime.date(next_year, next_month, 1) - datetime.timedelta(days=1)
).day
day = min(d.day, last_day)
return datetime.date(new_year, new_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 = d.year * 12 + (d.month - 1) + months
new_year, new_month0 = divmod(total, 12)
new_month = new_month0 + 1
last_day = calendar.monthrange(new_year, new_month)[1]
day = min(d.day, last_day)
return datetime.date(new_year, new_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 []
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(word.lower() for word in words)
sorted_items = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return sorted_items[: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)
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]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(word.lower() for word in 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 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 _flatten(prefix: str, value) -> None:
if isinstance(value, dict):
if not value:
result[prefix] = {}
else:
for key, val in value.items():
key = str(key)
new_prefix = f"{prefix}{sep}{key}" if prefix else key
_flatten(new_prefix, val)
elif isinstance(value, list):
if not value:
result[prefix] = []
else:
for idx, val in enumerate(value):
new_prefix = f"{prefix}{sep}{idx}" if prefix else str(idx)
_flatten(new_prefix, val)
else:
result[prefix] = value
for key, value in obj.items():
_flatten(str(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 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 _walk(value, prefix: str) -> None:
if isinstance(value, dict):
if not value:
if prefix:
result[prefix] = value
else:
for key, val in value.items():
new_prefix = f"{prefix}{sep}{key}" if prefix else str(key)
_walk(val, new_prefix)
elif isinstance(value, list):
if not value:
if prefix:
result[prefix] = value
else:
for idx, val in enumerate(value):
new_prefix = f"{prefix}{sep}{idx}" if prefix else str(idx)
_walk(val, new_prefix)
else:
if prefix:
result[prefix] = value
_walk(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: dict = {}
def walk(value, key):
if isinstance(value, dict):
if value:
for k, v in value.items():
walk(v, f"{key}{sep}{k}" if key else str(k))
elif key:
result[key] = {}
elif isinstance(value, list):
if value:
for i, v in enumerate(value):
walk(v, f"{key}{sep}{i}" if key else str(i))
elif key:
result[key] = []
else:
result[key] = value
walk(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
import functools
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
@functools.wraps(func)
def wrapper(*args):
if maxsize <= 0:
return func(*args)
if args in cache:
cache.move_to_end(args)
return cache[args]
result = func(*args)
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[args] = 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
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
def wrapper(*args):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args)
cache[key] = result
if 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__.
from collections import OrderedDict
def lru(maxsize: int):
def decorator(func):
cache: OrderedDict = OrderedDict()
def wrapper(*args):
if args in cache:
cache.move_to_end(args)
return cache[args]
result = func(*args)
cache[args] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator