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 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 ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + str(count))
count = 1
result.append(s[-1] + str(count))
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
def rle(s: str) -> str:
if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + str(count))
count = 1
result.append(s[-1] + str(count))
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
def rle(s: str) -> str:
if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + str(count))
count = 1
result.append(s[-1] + str(count))
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
def chunks(items, 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 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_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 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_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".
def round_half_up(value: str, digits: int) -> str:
from decimal import Decimal, ROUND_HALF_UP
value_dec = Decimal(value)
target = Decimal('1') / (Decimal('10') ** digits)
rounded = value_dec.quantize(target, 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".
def round_half_up(value: str, digits: int) -> str:
if digits == 0:
parts = value.split('.')
integer_part = parts[0]
fractional_part = parts[1] if len(parts) > 1 else ''
is_negative = value.startswith('-')
if fractional_part:
if fractional_part[0] >= '5':
integer_part_num = int(integer_part)
if is_negative:
integer_part_num -= 1
else:
integer_part_num += 1
return str(integer_part_num)
return integer_part
else:
parts = value.split('.')
integer_part = parts[0]
fractional_part = parts[1] if len(parts) > 1 else ''
if len(fractional_part) < digits:
rounded_part = fractional_part.ljust(digits, '0')
increment_needed = False
else:
rounded_part = fractional_part[:digits]
if len(fractional_part) > digits:
next_digit = fractional_part[digits]
increment_needed = next_digit >= '5'
else:
increment_needed = False
if increment_needed:
rounded_part_num = int(rounded_part) + 1
rounded_part_str = str(rounded_part_num)
if len(rounded_part_str) > digits:
carry = 1
fractional_part_new = rounded_part_str[-digits:]
else:
carry = 0
fractional_part_new = rounded_part_str.zfill(digits)
else:
carry = 0
fractional_part_new = rounded_part
integer_part_num = int(integer_part) + carry
result = f"{integer_part_num}.{fractional_part_new}"
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".
def round_half_up(value: str, digits: int) -> str:
from decimal import Decimal, ROUND_HALF_UP
value = value.replace(',', '') # Remove any commas
decimal_value = Decimal(value)
rounded = decimal_value.quantize(Decimal('1.' + '0' * digits), rounding=ROUND_HALF_UP)
if digits == 0:
return f"{rounded:.0f}"
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 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]:
result = {}
if not line:
return result
pairs = re.split(r'\s+', line)
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.
import re
def parse_kv(line: str) -> dict[str, str]:
result = {}
tokens = re.split(r'\s+', line.strip())
for token in tokens:
if not token:
continue
if '=' in token:
key, val = token.split('=', 1)
if val.startswith('"') and val.endswith('"'):
val = val[1:-1]
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 re
def parse_kv(line: str) -> dict[str, str]:
result = {}
tokens = re.findall(r'([a-zA-Z0-9_]+)=(".*?"|[^ ]+)', line)
for key, value in tokens:
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 = [list(sorted_intervals[0])]
for current in sorted_intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1])
else:
merged.append(list(current))
return [tuple(interval) for interval 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]]
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 = [list(sorted_intervals[0])]
for current in sorted_intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1])
else:
merged.append(list(current))
return [tuple(interval) for interval 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:
new_year = d.year + (d.month + months - 1) // 12
new_month = (d.month + months - 1) % 12 + 1
max_day = calendar.monthrange(new_year, new_month)[1]
new_day = d.day
if new_day > max_day:
new_day = max_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.
from datetime import date, timedelta
def add_months(d: date, months: int) -> date:
original_year = d.year
original_month = d.month
total_months = original_month + months
new_year = original_year + (total_months - 1) // 12
new_month = (total_months - 1) % 12 + 1
day = d.day
try:
return date(new_year, new_month, day)
except ValueError:
if new_month == 12:
next_month = 1
next_year = new_year + 1
else:
next_month = new_month + 1
next_year = new_year
last_day = date(next_year, next_month, 1) - timedelta(days=1)
return 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.
import datetime
def add_months(d: datetime.date, months: int) -> datetime.date:
original_year = d.year
original_month = d.month
total_months = original_month + months
new_year = original_year + (total_months - 1) // 12
new_month = (total_months - 1) % 12 + 1
if new_month == 12:
next_month = 1
next_year = new_year + 1
else:
next_month = new_month + 1
next_year = new_year
last_day = datetime.date(next_year, next_month, 1) - datetime.timedelta(days=1)
if d.day > last_day.day:
return last_day
else:
return datetime.date(new_year, new_month, 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 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)
words = [word.lower() for word in words]
counts = Counter(words)
sorted_counts = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
return sorted_counts[: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)
words_lower = [w.lower() for w in words]
counts = Counter(words_lower)
sorted_counts = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return sorted_counts[: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)
lower_words = [w.lower() for w in words]
counts = Counter(lower_words)
sorted_counts = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
return sorted_counts[: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:
def helper(current_path, obj):
result = {}
if isinstance(obj, dict):
for key in obj:
value = obj[key]
if isinstance(value, dict):
if not value:
new_key = current_path + sep + key
result[new_key] = value
else:
sub_result = helper(current_path + sep + key, value)
result.update(sub_result)
elif isinstance(value, list):
if not value:
new_key = current_path + sep + key
result[new_key] = value
else:
for i, element in enumerate(value):
sub_result = helper(current_path + sep + key + sep + str(i), element)
result.update(sub_result)
else:
new_key = current_path + sep + key
result[new_key] = value
elif isinstance(obj, list):
for i, element in enumerate(obj):
if isinstance(element, dict):
sub_result = helper(current_path + sep + str(i), element)
result.update(sub_result)
elif isinstance(element, list):
sub_result = helper(current_path + sep + str(i), element)
result.update(sub_result)
else:
new_key = current_path + sep + str(i)
result[new_key] = element
else:
result[current_path] = obj
return result
return helper("", obj)
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(d, prefix=""):
if isinstance(d, dict):
for k, v in d.items():
new_prefix = f"{prefix}{k}" if prefix else k
_flatten(v, new_prefix + sep)
elif isinstance(d, list):
for i, item in enumerate(d):
_flatten(item, f"{prefix}{i}" + sep)
else:
result[prefix.rstrip(sep)] = d
_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": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def _flatten(d, prefix=""):
if isinstance(d, dict):
for k, v in d.items():
new_prefix = f"{prefix}{k}" if prefix else k
_flatten(v, new_prefix + sep)
elif isinstance(d, list):
for i, item in enumerate(d):
_flatten(item, f"{prefix}{i}" + sep)
else:
result[prefix[:-1]] = d if isinstance(d, (dict, list)) else d
_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):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
else:
value = func(*args)
cache[key] = value
if len(cache) > maxsize:
cache.popitem(last=False)
return value
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__.
def lru(maxsize: int):
def decorator(func):
cache = {}
lru_order = []
def wrapper(*args):
if args in cache:
lru_order.remove(args)
lru_order.append(args)
return cache[args]
if len(cache) >= maxsize:
least_used = lru_order.pop(0)
del cache[least_used]
lru_order.append(args)
cache[args] = func(*args)
return cache[args]
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__.
def lru(maxsize: int):
def decorator(func):
cache = {}
lru_order = []
def wrapper(*args):
if args in cache:
lru_order.remove(args)
lru_order.append(args)
return cache[args]
if len(cache) >= maxsize:
least_used = lru_order.pop(0)
del cache[least_used]
lru_order.append(args)
cache[args] = func(*args)
return cache[args]
wrapper.__name__ = func.__name__
return wrapper
return decorator