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:
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return 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:
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return 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 s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
result.append(f"{current_char}{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 ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
result.append(f"{current_char}{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 ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
result.append(f"{current_char}{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.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(itertools.islice(items, i, i + n)) for i in range(0, len(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 typing import Iterable, Iterator, List
def chunks(items: Iterable, n: int) -> List[List]:
if n < 1:
raise ValueError("n must be at least 1")
iterator = iter(items)
while True:
chunk = []
for _ in range(n):
try:
chunk.append(next(iterator))
except StopIteration:
if chunk:
yield chunk
return
yield 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.
from collections.abc import Iterable
def chunks(items: Iterable, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
result = []
current_chunk = []
for item in items:
current_chunk.append(item)
if len(current_chunk) == n:
result.append(current_chunk)
current_chunk = []
if current_chunk:
result.append(current_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 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".
import math
def round_half_up(value: str, digits: int) -> str:
if '.' in value:
integer_part, fractional_part = value.split('.')
if digits == 0:
return integer_part
rounded = float(value)
rounded = math.floor(rounded * (10 ** digits) + 0.5) / (10 ** digits)
rounded_str = "{0:.{1}f}".format(rounded, digits)
return rounded_str
else:
if digits == 0:
return value
rounded = float(value)
rounded = math.floor(rounded * (10 ** digits) + 0.5) / (10 ** digits)
rounded_str = "{0:.{1}f}".format(rounded, digits)
return rounded_str
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".
def round_half_up(value: str, digits: int) -> str:
if '.' in value:
integer_part, fractional_part = value.split('.', 1)
else:
integer_part, fractional_part = value, ''
if digits == 0:
if not fractional_part:
return integer_part
rounded = int(integer_part) + (int(fractional_part) + 9**len(fractional_part)) // (10**len(fractional_part))
return str(rounded)
fractional_part = fractional_part.ljust(digits + 1, '0')[:digits + 1]
if len(fractional_part) <= digits:
fractional_part += '0' * (digits - len(fractional_part))
if len(fractional_part) > digits:
carry = int(fractional_part[digits]) + (1 if fractional_part[digits + 1] >= '5' else 0)
if carry >= 10:
carry = 0
if digits == 0:
integer_part = str(int(integer_part) + 1)
else:
integer_part = str(int(integer_part) + 1)
fractional_part = '0' * digits
else:
fractional_part = fractional_part[:digits]
fractional_part = fractional_part[:digits] + str(carry)
if carry >= 10:
integer_part = str(int(integer_part) + 1)
fractional_part = '0' * digits
result = integer_part
if digits > 0:
result += '.' + fractional_part.ljust(digits, '0')[:digits]
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".
import math
def round_half_up(value: str, digits: int) -> str:
if '.' in value:
num, frac = value.split('.', 1)
frac += '0' * (digits - len(frac))
if len(frac) > digits:
frac = frac[:digits]
if len(frac) < digits:
frac += '0' * (digits - len(frac))
if len(frac) > digits:
frac = frac[:digits]
if len(frac) == digits:
last_digit = int(frac[-1])
if last_digit >= 5:
frac = str(int(frac[:-1]) + 1)
if len(frac) > digits:
frac = frac[:-1] + frac[-1]
if len(frac) > digits:
frac = frac[:-1] + frac[-1]
if len(frac) > digits:
frac = frac[:-1] + frac[-1]
frac = frac.ljust(digits, '0')[:digits]
num = str(int(num) + int(frac[:-digits] + frac[-digits:]) // (10 ** digits))
frac = frac[-digits:]
if len(frac) < digits:
frac += '0' * (digits - len(frac))
result = f"{num}.{frac}" if digits > 0 else num
else:
if digits == 0:
result = value
else:
result = f"{value}.0" * digits
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]:
if not line.strip():
return {}
pattern = re.compile(r'([^=\s]+)=([^\s"]*|"[^"]*")')
matches = pattern.findall(line)
result = {}
for key, value in matches:
stripped_value = value.strip('"') if value.startswith('"') and value.endswith('"') else value
result[key] = stripped_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.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
pattern = re.compile(r'([^= \t]+)=("([^"]*)"|([^ \t]+))')
result = {}
for match in pattern.finditer(line):
key = match.group(1)
value = match.group(3) if match.group(3) else match.group(4)
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.strip():
return {}
result = {}
parts = line.split('=')
for part in parts:
if not part.strip():
continue
key_part, value_part = part.split(maxsplit=1)
key = key_part.strip()
value = value_part.strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
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]]
for current in sorted_intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
new_start = last[0]
new_end = max(last[1], current[1])
merged[-1] = (new_start, new_end)
else:
merged.append(current)
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 x: x[0])
merged = [sorted_intervals[0]]
for current_start, current_end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if current_start <= last_end:
new_start = last_start
new_end = max(last_end, current_end)
merged[-1] = (new_start, new_end)
else:
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 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]]
for current_start, current_end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if current_start <= last_end:
new_start = last_start
new_end = max(last_end, current_end)
merged[-1] = (new_start, new_end)
else:
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 datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
year = d.year
month = d.month + months
last_day = datetime.date(year, month, 1) - datetime.timedelta(days=1)
return datetime.date(year=last_day.year, month=last_day.month, day=last_day.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.
from datetime import date, timedelta
def add_months(d: date, months: int) -> date:
year = d.year + months // 12
month = d.month + months % 12
if month < 1:
year -= 1
month += 12
elif month > 12:
year += 1
month -= 12
last_day = (date(year, month + 1, 1) - timedelta(days=1)).day
return date(year, month, min(d.day, last_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.
from datetime import date, timedelta
def add_months(d: date, months: int) -> date:
year = d.year + months // 12
month = d.month + months % 12
if month < 1:
year -= 1
month += 12
elif month > 12:
year += 1
month -= 12
last_day = date(year, month, 1) + timedelta(days=32)
return date(last_day.year, last_day.month, last_day.day - 1)
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 defaultdict
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = defaultdict(int)
for word in words:
lower_word = word.lower()
counts[lower_word] += 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 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 defaultdict
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = defaultdict(int)
for word in words:
lower_word = word.lower()
counts[lower_word] += 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 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 defaultdict
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = defaultdict(int)
for word in words:
lower_word = word.lower()
counts[lower_word] += 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(current, prefix=""):
if isinstance(current, dict):
for key, value in current.items():
new_prefix = f"{prefix}{sep}{key}" if prefix else key
if isinstance(value, (dict, list)):
_flatten(value, new_prefix)
else:
result[new_prefix] = value
elif isinstance(current, list):
for index, item in enumerate(current):
new_prefix = f"{prefix}{sep}{index}"
if isinstance(item, (dict, list)):
_flatten(item, new_prefix)
else:
result[new_prefix] = item
for key, value in obj.items():
if isinstance(value, (dict, list)):
_flatten(value, key)
else:
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 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": {}}.
from typing import Any
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def _flatten(current: Any, prefix: str = "") -> None:
if isinstance(current, dict):
for key, value in current.items():
new_key = f"{prefix}{sep}{key}" if prefix else key
if isinstance(value, (dict, list)):
_flatten(value, new_key)
else:
result[new_key] = value
elif isinstance(current, list):
for idx, item in enumerate(current):
new_key = f"{prefix}{sep}{idx}"
if isinstance(item, (dict, list)):
_flatten(item, new_key)
else:
result[new_key] = item
for key, value in obj.items():
if isinstance(value, (dict, list)):
_flatten(value, key)
else:
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 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(nested, key_prefix=""):
if isinstance(nested, dict):
for k, v in nested.items():
new_key = f"{key_prefix}{sep}{k}" if key_prefix else k
if isinstance(v, (dict, list)):
_flatten(v, new_key)
else:
result[new_key] = v
elif isinstance(nested, list):
for i, item in enumerate(nested):
new_key = f"{key_prefix}{sep}{i}"
if isinstance(item, (dict, list)):
_flatten(item, new_key)
else:
result[new_key] = item
for k, v in obj.items():
if isinstance(v, (dict, list)):
_flatten(v, k)
else:
result[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):
cache = OrderedDict()
cache_hits = 0
def decorator(func):
def wrapper(*args):
nonlocal cache, cache_hits
key = args
if key in cache:
cache.move_to_end(key)
cache_hits += 1
return cache[key]
result = func(*args)
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = result
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 wrapped(*args):
nonlocal cache
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
wrapped.__name__ = func.__name__
return wrapped
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()
func.__name__ = func.__name__
def wrapper(*args):
if args in cache:
cache.move_to_end(args)
return cache[args]
if len(cache) >= maxsize:
cache.popitem(last=False)
result = func(*args)
cache[args] = result
return result
return wrapper
return decorator