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 True if year is a leap year in the Gregorian calendar."""
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_char = s[0]
count = 1
for ch in s[1:]:
if ch == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = ch
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 = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
result.append(f"{prev}{count}")
prev = ch
count = 1
result.append(f"{prev}{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:
result = []
i = 0
n = len(s)
while i < n:
ch = s[i]
j = i + 1
while j < n and s[j] == ch:
j += 1
result.append(f"{ch}{j - i}")
i = j
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, Any
def chunks(items: Iterable[Any], n: int) -> list[list[Any]]:
if n < 1:
raise ValueError("n must be >= 1")
result: list[list[Any]] = []
buffer: list[Any] = []
for item in items:
buffer.append(item)
if len(buffer) == n:
result.append(buffer)
buffer = []
if buffer:
result.append(buffer)
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 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, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
dec = Decimal(value)
quant = Decimal(f"1e{-digits}")
rounded = dec.quantize(quant, rounding=ROUND_HALF_UP)
return str(rounded)
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:
d = Decimal(value)
exp = Decimal('1') if digits == 0 else Decimal(f'1e-{digits}')
with localcontext() as ctx:
ctx.prec = max(len(value.replace('-', '').replace('.', '')), digits + 10)
rounded = d.quantize(exp, rounding=ROUND_HALF_UP)
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".
import decimal
def round_half_up(value: str, digits: int) -> str:
d = decimal.Decimal(value)
exp = decimal.Decimal('1') if digits == 0 else decimal.Decimal('1.' + '0' * digits)
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_HALF_UP
rounded = d.quantize(exp, context=ctx)
s = format(rounded, 'f')
if digits == 0:
s = s.split('.')[0]
return 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 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]:
"""Parse a line of key=value pairs separated by spaces.
Values may be quoted with double quotes to include spaces or '='.
If a key repeats, the last value is kept.
"""
if not line.strip():
return {}
result: dict[str, str] = {}
i = 0
n = len(line)
while i < n:
# Skip leading spaces
while i < n and line[i].isspace():
i += 1
if i >= n:
break
# Parse key
key_start = i
while i < n and line[i] != '=':
i += 1
if i >= n:
break # no '=' found, ignore rest
key = line[key_start:i]
i += 1 # skip '='
# Parse value
if i < n and line[i] == '"':
i += 1 # skip opening quote
val_start = i
while i < n and line[i] != '"':
i += 1
val = line[val_start:i]
if i < n and line[i] == '"':
i += 1 # skip closing quote
else:
val_start = i
while i < n and not line[i].isspace():
i += 1
val = line[val_start:i]
result[key] = val
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
import shlex
def parse_kv(line: str) -> dict[str, str]:
"""Parse a line of key=value pairs separated by spaces, with optional quoted values."""
tokens = shlex.split(line)
result: dict[str, str] = {}
for token in tokens:
if '=' not in token:
continue
key, value = token.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.
import shlex
from typing import Dict
def parse_kv(line: str) -> Dict[str, str]:
if not line.strip():
return {}
result: Dict[str, str] = {}
for token in shlex.split(line):
if '=' not in token:
continue
key, value = token.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 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.
from __future__ import annotations
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
# Work on a sorted copy to keep the original unchanged
sorted_intervals = sorted(intervals, key=lambda i: (i[0], i[1]))
merged: list[tuple[int, int]] = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end: # overlapping or touching
if end > current_end:
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 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 []
# Work on a sorted copy to avoid modifying the input
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged: list[tuple[int, int]] = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end: # Overlap or touch
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 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.
from typing import List, Tuple
def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort a copy of the intervals by start, then by end
sorted_intervals = sorted(intervals, key=lambda iv: (iv[0], iv[1]))
merged: List[Tuple[int, int]] = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end: # overlap or touch
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 datetime
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
new_month = d.month + months
year_delta, new_month_index = divmod(new_month - 1, 12)
new_year = d.year + year_delta
new_month = new_month_index + 1
last_day = calendar.monthrange(new_year, new_month)[1]
new_day = min(d.day, last_day)
return datetime.date(new_year, new_month, new_day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write add_months(d: datetime.date, months: int) -> datetime.date to add months calendar months to d. months may be negative. If the day does not exist in the target month, use the last day of that month.
import datetime
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
"""
Add `months` calendar months to the date `d`. Handles negative offsets
and adjusts the day to the last valid day of the target month if necessary.
"""
# Calculate the target year and month
month_offset = d.month - 1 + months
new_year = d.year + month_offset // 12
new_month = month_offset % 12 + 1
# Determine the last day of the target month
last_day = calendar.monthrange(new_year, new_month)[1]
# Adjust the day if it exceeds the last day of the target month
new_day = min(d.day, last_day)
return datetime.date(new_year, new_month, new_day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write add_months(d: datetime.date, months: int) -> datetime.date to add months calendar months to d. months may be negative. If the day does not exist in the target month, use the last day of that month.
import datetime
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
total_month = d.month + months
new_year, new_month = divmod(total_month - 1, 12)
new_year += d.year
new_month += 1
last_day = calendar.monthrange(new_year, new_month)[1]
new_day = d.day if d.day <= last_day else last_day
return datetime.date(new_year, new_month, new_day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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
from typing import List, Tuple
def top_k_words(text: str, k: int) -> List[Tuple[str, int]]:
words = re.findall(r"[A-Za-z']+", text)
counts = Counter(word.lower() for word in words)
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 Counter
from typing import List, Tuple
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_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.
ktrailing = 0 # placeholder to avoid unused import warnings
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)
counter = Counter(word.lower() for word in words)
sorted_items = sorted(counter.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 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:
if not isinstance(obj, dict):
raise TypeError("obj must be a dict")
if not obj:
return {}
result = {}
def _recurse(value, path):
if isinstance(value, dict):
if not value:
result[path] = {}
return
for k, v in value.items():
new_path = f"{path}{sep}{k}" if path else k
_recurse(v, new_path)
elif isinstance(value, list):
if not value:
result[path] = []
return
for idx, item in enumerate(value):
new_path = f"{path}{sep}{idx}" if path else str(idx)
_recurse(item, new_path)
else:
result[path] = value
_recurse(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
def flatten(obj: Dict[str, Any], sep: str = ".") -> Dict[str, Any]:
result: Dict[str, Any] = {}
def _flatten(value: Any, prefix: str) -> None:
if isinstance(value, dict):
if not value:
result[prefix] = {}
return
for k, v in value.items():
new_prefix = f"{prefix}{sep}{k}" if prefix else k
_flatten(v, new_prefix)
elif isinstance(value, list):
if not value:
result[prefix] = []
return
for i, v in enumerate(value):
new_prefix = f"{prefix}{sep}{i}" if prefix else str(i)
_flatten(v, new_prefix)
else:
result[prefix] = value
for key, val in obj.items():
_flatten(val, key)
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:
"""
Flatten nested dictionaries and lists into a single-level dictionary.
Keys from nested structures are concatenated using `sep`.
List indices are used as keys.
Empty dictionaries or lists are preserved as values.
"""
result: dict = {}
def _flatten(value, path: str) -> None:
if isinstance(value, dict):
if not value:
result[path] = value
else:
for k, v in value.items():
new_path = f"{path}{sep}{k}" if path else str(k)
_flatten(v, new_path)
elif isinstance(value, list):
if not value:
result[path] = value
else:
for i, v in enumerate(value):
new_path = f"{path}{sep}{i}" if path else str(i)
_flatten(v, new_path)
else:
result[path] = value
_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__.
import collections
import functools
def lru(maxsize: int):
def decorator(func):
cache = collections.OrderedDict()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
if maxsize > 0:
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = result
return result
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
import collections
from functools import wraps
def lru(maxsize: int):
def decorator(func):
cache = collections.OrderedDict()
@wraps(func)
def wrapper(*args):
if maxsize <= 0:
return func(*args)
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args)
cache[key] = result
cache.move_to_end(key)
if len(cache) > maxsize:
cache.popitem(last=False)
return result
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
import collections
import functools
def lru(maxsize: int):
"""Return a decorator that caches up to `maxsize` results using LRU eviction."""
if maxsize <= 0:
raise ValueError("maxsize must be a positive integer")
def decorator(func):
cache = collections.OrderedDict()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = args # cache only by positional arguments
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) # remove least recently used
return result
return wrapper
return decorator