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 "".
import itertools
def rle(s: str) -> str:
return "".join(ch + str(sum(1 for _ in g)) for ch, g 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:
from itertools import groupby
return "".join(f"{ch}{len(list(g))}" for ch, g 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 "".
def rle(s: str) -> str:
if not s:
return ""
res = []
cur = s[0]
count = 1
for ch in s[1:]:
if ch == cur:
count += 1
else:
res.append(cur + str(count))
cur = ch
count = 1
res.append(cur + str(count))
return "".join(res)
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")
it = iter(items)
result = []
while True:
chunk = []
try:
for _ in range(n):
chunk.append(next(it))
except StopIteration:
if chunk:
result.append(chunk)
return result
result.append(chunk)
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 = []
chunk = []
for item in items:
chunk.append(item)
if len(chunk) == n:
result.append(chunk)
chunk = []
if chunk:
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 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:
d = Decimal(value)
if digits == 0:
quant = Decimal('1')
else:
quant = Decimal('0.' + '0' * digits)
rounded = d.quantize(quant, rounding=ROUND_HALF_UP)
return format(rounded, f'.{digits}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:
d = Decimal(value)
if digits == 0:
quant = Decimal('1')
else:
quant = Decimal('0.' + '0' * (digits - 1) + '1')
rounded = d.quantize(quant, rounding=ROUND_HALF_UP)
if digits == 0:
return format(rounded, 'f')
return format(rounded, f'.{digits}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:
d = Decimal(value)
exp = Decimal(10) ** -digits
rounded = d.quantize(exp, rounding=ROUND_HALF_UP)
return format(rounded, f".{digits}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].isspace():
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=':
i += 1
key = line[key_start:i]
i += 1 # skip '='
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 not line[i].isspace():
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]:
if not line or line.strip() == "":
return {}
result: dict[str, str] = {}
tokens: list[str] = []
current: list[str] = []
in_quote = False
for ch in line:
if ch == '"':
in_quote = not in_quote
current.append(ch)
elif ch.isspace() and not in_quote:
if current:
tokens.append("".join(current))
current = []
else:
current.append(ch)
if current:
tokens.append("".join(current))
for token in tokens:
if "=" not in token:
continue
key, value_part = token.split("=", 1)
if len(value_part) >= 2 and value_part.startswith('"') and value_part.endswith('"'):
value = value_part[1:-1]
else:
value = value_part
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 True:
while i < n and line[i].isspace():
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=':
i += 1
key = line[key_start:i]
if i < n and line[i] == '=':
i += 1
else:
# malformed: no equals, break
break
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 not line[i].isspace():
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 x: x[0])
merged = [[sorted_intervals[0][0], sorted_intervals[0][1]]]
for s, e in sorted_intervals[1:]:
last_s, last_e = merged[-1]
if s <= last_e:
if e > last_e:
merged[-1][1] = e
else:
merged.append([s, e])
return [(s, e) for s, e in 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 x: x[0])
merged = [list(sorted_intervals[0])]
for start, end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end + 1:
if end > last_end:
merged[-1][1] = end
else:
merged.append([start, end])
return [tuple(m) for m in 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 x: x[0])
merged = [[sorted_intervals[0][0], sorted_intervals[0][1]]]
for s, e in sorted_intervals[1:]:
last_s, last_e = merged[-1]
if s <= last_e:
merged[-1][1] = max(last_e, e)
else:
merged.append([s, e])
return [tuple(x) for x in 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 datetime
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
total = d.year * 12 + (d.month - 1) + months
year = total // 12
month = total % 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 datetime
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.month - 1 + months
year = d.year + total_months // 12
month = total_months % 12 + 1
if month <= 0:
month += 12
year -= 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
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
total = d.month - 1 + months
year = d.year + total // 12
month = total % 12 + 1
max_day = calendar.monthrange(year, month)[1]
day = min(d.day, max_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]]:
words = re.finditer(r"[A-Za-z']+", text)
counts = Counter(m.group().lower() for m 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]]:
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(w.lower() for w in words)
return sorted(counts.items(), key=lambda x: (-x[1], x[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.
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
counts = {}
i = 0
n = len(text)
while i < n:
ch = text[i]
if ('a' <= ch <= 'z') or ('A' <= ch <= 'Z') or ch == "'":
j = i + 1
while j < n:
c = text[j]
if ('a' <= c <= 'z') or ('A' <= c <= 'Z') or c == "'":
j += 1
else:
break
word = text[i:j].lower()
counts[word] = counts.get(word, 0) + 1
i = j
else:
i += 1
sorted_words = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return sorted_words[: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(value, key: str):
if isinstance(value, dict):
if not value:
result[key] = value
return
for k, v in value.items():
new_key = f"{key}{sep}{k}"
_flatten(v, new_key)
elif isinstance(value, list):
if not value:
result[key] = value
return
for i, item in enumerate(value):
new_key = f"{key}{sep}{i}"
_flatten(item, new_key)
else:
result[key] = value
for k, v in obj.items():
_flatten(v, str(k))
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(value, prefix: str):
if isinstance(value, dict):
if not value:
result[prefix] = value
else:
for k, v in value.items():
key = str(k)
new_prefix = f"{prefix}{sep}{key}" if prefix else key
_flatten(v, new_prefix)
elif isinstance(value, list):
if not value:
result[prefix] = value
else:
for i, v in enumerate(value):
key = str(i)
new_prefix = f"{prefix}{sep}{key}" if prefix else key
_flatten(v, new_prefix)
else:
result[prefix] = value
for k, v in obj.items():
_flatten(v, str(k))
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(prefix: str, value):
if isinstance(value, dict):
if not value:
result[prefix] = {}
else:
for k, v in value.items():
new_key = f"{prefix}{sep}{k}" if prefix else k
_flatten(new_key, v)
elif isinstance(value, list):
if not value:
result[prefix] = []
else:
for i, v in enumerate(value):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
_flatten(new_key, v)
else:
result[prefix] = value
for k, v in obj.items():
_flatten(k, v)
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
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
def wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
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()
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):
if maxsize <= 0:
def wrapper(*args):
return func(*args)
wrapper.__name__ = func.__name__
return wrapper
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