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.
from datetime import datetime
def is_leap(year: int) -> bool:
return datetime(year, 2, 29).isocalendar()[1] % 4 == 0 and (datetime(year, 2, 29).isocalendar()[1] % 100 != 0 or datetime(year, 2, 29).isocalendar()[1] % 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.
from datetime import datetime
def is_leap(year: int) -> bool:
return datetime(year, 2, 29).isocalendar()[1] == 29
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 ""
encoded = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
encoded.append(f"{current_char}{count}")
current_char = char
count = 1
encoded.append(f"{current_char}{count}")
return "".join(encoded)
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.
from typing import Iterable, TypeVar, List
T = TypeVar('T')
def chunks(items: Iterable[T], n: int) -> List[List[T]]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(items.__next__() for _ in range(n)) if (items := iter(items)) else []]
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(items_n) for items_n in itertools.islice(items, None, None, 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, TypeVar, List
T = TypeVar('T')
def chunks(items: Iterable[T], n: int) -> List[List[T]]:
if n < 1:
raise ValueError("n must be at least 1")
return [list(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 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 digits < 0:
raise ValueError("digits must be non-negative")
if digits == 0:
return str(int(float(value)))
decimal_part = value.split('.')
integer_part = decimal_part[0]
fractional_part = decimal_part[1] if len(decimal_part) > 1 else '0'
if len(fractional_part) <= digits:
return f"{integer_part}.{'0' * digits}"
fractional_part = fractional_part[-digits-1:]
if len(fractional_part) == digits:
rounded = int(fractional_part)
if rounded % 2 == 0:
fractional_part = fractional_part[:-1]
else:
fractional_part = str(int(fractional_part) + 1)
else:
fractional_part = fractional_part[-digits:]
if len(fractional_part) < digits:
fractional_part = fractional_part.ljust(digits, '0')
else:
rounded = int(fractional_part[:digits])
if rounded % 2 == 0:
fractional_part = fractional_part[:digits-1]
else:
fractional_part = str(int(fractional_part[:digits]) + 1)
if digits == 0:
return integer_part
else:
return f"{integer_part}.{fractional_part}"
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 decimal
def round_half_up(value: str, digits: int) -> str:
num = decimal.Decimal(value)
rounded = num.quantize(decimal.Decimal(f'1.0' + '0' * digits), rounding=decimal.ROUND_HALF_UP)
if digits == 0:
return str(int(rounded))
return f"{rounded:.{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".
def round_half_up(value: str, digits: int) -> str:
if digits < 0:
raise ValueError("Digits must be non-negative")
if digits == 0:
return str(int(float(value)))
decimal_part = value.split('.')
if len(decimal_part) == 1:
decimal_part.append('0') * digits
num = float(value)
else:
num = float(value)
decimal_part = decimal_part[1]
if len(decimal_part) < digits:
decimal_part += '0' * (digits - len(decimal_part))
else:
decimal_part = decimal_part[:digits]
scale = 10 ** digits
rounded = int(num * scale + 0.5) / scale
if digits == 0:
return str(int(rounded))
else:
return f"{int(rounded):.{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]:
if not line.strip():
return {}
pairs = []
current_pair = []
in_quotes = False
for char in line:
if char == '"':
in_quotes = not in_quotes
elif char == '=' and not in_quotes:
if current_pair:
pairs.append(''.join(current_pair))
current_pair = []
else:
current_pair.append(char)
if current_pair:
pairs.append(''.join(current_pair))
result = {}
for pair in pairs:
if '=' in pair:
key, value = pair.split('=', 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 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.
from typing import Dict
def parse_kv(line: str) -> Dict[str, str]:
if not line.strip():
return {}
pairs = line.split()
result: Dict[str, str] = {}
for pair in pairs:
if '=' in pair:
key, value = pair.split('=', 1)
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 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 {}
pairs = []
current_pair = []
in_quotes = False
for char in line:
if char == '"':
in_quotes = not in_quotes
if char == '=' and not in_quotes:
pairs.append(''.join(current_pair).strip())
current_pair = []
else:
current_pair.append(char)
if current_pair:
pairs.append(''.join(current_pair).strip())
result = {}
for pair in pairs:
if '=' in pair:
key, value = pair.split('=', 1)
result[key.strip()] = value.strip().strip('"')
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 []
intervals_sorted = sorted(intervals, key=lambda x: x[0])
merged = [intervals_sorted[0]]
for current_start, current_end in intervals_sorted[1:]:
last_start, last_end = merged[-1]
if current_start <= last_end:
merged[-1] = (last_start, max(last_end, current_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 in sorted_intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
merged[-1] = (last[0], max(last[1], current[1]))
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 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, month = d.year + months, d.month
if month > 12:
year += month // 12
month %= 12
elif month < 1:
year += month // 12
month %= 12
last_day = date(year, month + 1, 1) - timedelta(days=1)
return date(year, month, min(d.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 > 12:
month -= 12
elif month < 1:
month += 12
last_day = d.replace(year=year, month=month).replace(day=1) - timedelta(days=1)
return d.replace(year=year, month=month, day=min(last_day.day, d.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, month = d.year + months, d.month
while True:
try:
last_day = date(year, month, 1) + timedelta(days=32)
return date(year, month, last_day.day)
except ValueError:
month += 1
if month > 12:
year += 1
month = 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.
from collections import defaultdict
from typing import List, Tuple
def top_k_words(text: str, k: int) -> List[Tuple[str, int]]:
word_counts = defaultdict(int)
words = re.findall(r"[a-zA-Z']+", text)
for word in words:
lower_word = word.lower()
word_counts[lower_word] += 1
sorted_words = sorted(
word_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)
word_counts = defaultdict(int)
for word in words:
lower_word = word.lower()
word_counts[lower_word] += 1
sorted_words = sorted(word_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)
word_counts = defaultdict(int)
for word in words:
lower_word = word.lower()
word_counts[lower_word] += 1
sorted_words = sorted(word_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, parent_key):
if isinstance(current, dict):
for k, v in current.items():
_flatten(v, f"{parent_key}{sep}{k}" if parent_key else k)
elif isinstance(current, list):
for i, v in enumerate(current):
_flatten(v, f"{parent_key}{sep}{i}")
else:
result[parent_key] = 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": {}}.
from typing import Any, Dict, Union, List
def flatten(obj: Dict[Any, Union[Dict[Any, Any], List[Any], Any]], sep: str = ".") -> Dict[str, Any]:
result: Dict[str, Any] = {}
def _flatten(current: Union[Dict[Any, Any], List[Any], Any], parent_key: str = "") -> None:
if isinstance(current, dict):
for key, value in current.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
_flatten(value, new_key)
elif isinstance(current, list):
for index, item in enumerate(current):
new_key = f"{parent_key}{sep}{index}" if parent_key else str(index)
_flatten(item, new_key)
else:
result[parent_key] = 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": {}}.
from typing import Any, Dict, List, Union
def flatten(obj: Dict[Any, Union[Dict[Any, Any], List[Any]]], sep: str = ".") -> Dict[str, Union[Dict[Any, Any], List[Any]]]:
result: Dict[str, Any] = {}
def _flatten(current: Any, parent_key: str = "") -> None:
if isinstance(current, dict):
for key, value in current.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
_flatten(value, new_key)
elif isinstance(current, list):
for index, item in enumerate(current):
new_key = f"{parent_key}{sep}{index}" if parent_key else str(index)
_flatten(item, new_key)
else:
result[parent_key] = 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
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
def wrapper(*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
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, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
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 wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = result
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator