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 whether `year` is a leap year in the Gregorian calendar.
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
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 whether `year` is a leap year in the Gregorian calendar.
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
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 whether `year` is a leap year in the Gregorian calendar.
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
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:
"""
Performs 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 "".
"""
if not s:
return ""
result = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result += s[i - 1] + str(count)
count = 1
result += s[-1] + str(count)
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 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:
"""
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 ""
"""
if not s:
return ""
result = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result += s[i - 1] + str(count)
count = 1
result += s[-1] + str(count)
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 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:
"""
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 "".
"""
if not s:
return ""
result = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result += s[i - 1] + str(count)
count = 1
result += s[-1] + str(count)
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 greater than or equal to 1")
it = iter(items)
while True:
chunk = list(itertools.islice(it, n))
if not chunk:
return
yield chunk
import itertools
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
it = iter(items)
while True:
chunk = []
try:
for _ in range(n):
chunk.append(next(it))
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.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("Chunk size must be at least 1")
it = iter(items)
while True:
chunk = list(itertools.islice(it, n))
if not chunk:
return
yield chunk
import itertools
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:
value = float(value)
rounded_value = round(value, digits)
if digits == 0:
return str(int(rounded_value))
else:
return "{:.{}f}".format(rounded_value, digits)
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:
try:
num = float(value)
rounded_num = round(num, digits)
if digits > 0:
return str(rounded_num)
else:
return str(int(rounded_num))
except ValueError:
return value
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:
value = float(value)
rounded_value = round(value, digits)
s = str(rounded_value)
if '.' not in s:
return s
if s.startswith('.') and len(s.split('.')[1]) < digits:
return s
if s.endswith('.') and len(s.split('.')[0]) < digits:
return s
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]:
result = {}
if not line:
return result
pairs = line.split()
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.
def 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.
"""
result = {}
if not line:
return result
for pair in line.split():
if "=" in pair:
key, value = pair.split("=", 1)
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
result[key] = value
elif pair:
result[pair] = ""
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]:
"""
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.
"""
result = {}
if not line:
return result
pairs = line.split()
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
elif pair:
result[pair] = ""
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.sort()
merged = [intervals[0]]
for start, end in intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, max(last_end, end))
else:
merged.append((start, 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 []
intervals.sort()
merged = [intervals[0]]
for start, end in intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, max(last_end, end))
else:
merged.append((start, 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 []
intervals.sort()
merged = [intervals[0]]
for start, end in intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, max(last_end, end))
else:
merged.append((start, 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:
month = d.month - 1 + months
year = d.year + month // 12
month = month % 12 + 1
day = d.day
try:
return datetime.date(year, month, day)
except ValueError:
import calendar
last_day = calendar.monthrange(year, month)[1]
return datetime.date(year, month, 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:
"""Adds months to a date.
Args:
d: The date to add months to.
months: The number of months to add.
Returns:
The new date after adding months.
"""
month = d.month - 1 + months
year = d.year + month // 12
month = month % 12 + 1
day = d.day
try:
return datetime.date(year, month, day)
except ValueError:
# Handle cases where the day doesn't exist in the target month
if month == 2:
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
# Leap year
return datetime.date(year, month, 29)
else:
return datetime.date(year, month, 28)
elif month in [4, 6, 9, 11]:
return datetime.date(year, month, 30)
else:
return datetime.date(year, month, 31)
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:
month = d.month - 1 + months
year = d.year + month // 12
month = month % 12 + 1
day = d.day
try:
return datetime.date(year, month, day)
except ValueError:
if month == 2:
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return datetime.date(year, month, 29)
else:
return datetime.date(year, month, 28)
elif month in [4, 6, 9, 11]:
return datetime.date(year, month, 30)
else:
return datetime.date(year, month, 31)
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 Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = []
current_word = ""
for char in text:
if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or char == '\'' :
current_word += char.lower()
else:
if current_word:
words.append(current_word)
current_word = ""
if current_word:
words.append(current_word)
word_counts = Counter(words)
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.
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = []
current_word = ""
for char in text:
if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or char == '\'' :
current_word += char.lower()
else:
if current_word:
words.append(current_word)
current_word = ""
if current_word:
words.append(current_word)
word_counts = Counter(words)
return sorted(word_counts.items(), key=lambda item: (-item[1], item[0]))[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = []
for word in text.lower().split():
clean_word = ''.join(c for c in word if c.isalpha() or c == "'")
if clean_word:
words.append(clean_word)
word_counts = Counter(words)
return sorted(word_counts.items(), key=lambda item: (-item[1], item[0]))[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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 = {}
for key, value in obj.items():
if isinstance(value, dict):
result.update(flatten(value, sep=sep).items())
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
result.update(flatten(item, sep=sep).items())
else:
result[key + sep + str(i)] = item
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 = {}
for key, value in obj.items():
if isinstance(value, dict):
for k, v in flatten(value, sep=sep).items():
result[key + sep + k] = v
elif isinstance(value, list):
for i, v in enumerate(value):
if isinstance(v, dict):
for k, w in flatten(v, sep=sep).items():
result[key + sep + str(i) + sep + k] = w
else:
result[key + sep + str(i)] = v
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 = {}
for k, v in obj.items():
if isinstance(v, dict):
result.update(flatten(v, sep=sep).items())
elif isinstance(v, list):
for i, elem in enumerate(v):
if isinstance(elem, dict):
result.update(flatten(elem, sep=sep).items())
else:
result[k + f"." + str(i)] = elem
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__.
def lru(maxsize: int):
def decorator_factory(func):
cache = {}
usage = []
def wrapper(*args):
if args in cache:
usage.remove(args)
usage.append(args)
return cache[args]
else:
result = func(*args)
cache[args] = result
usage.append(args)
if len(cache) > maxsize:
oldest = usage.pop(0)
del cache[oldest]
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator_factory
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_factory(func):
cache = {}
usage = []
def wrapper(*args):
if args in cache:
usage.remove(args)
usage.append(args)
return cache[args]
else:
result = func(*args)
cache[args] = result
usage.append(args)
if len(cache) > maxsize:
oldest = usage.pop(0)
del cache[oldest]
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator_factory
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_factory(func):
cache = {}
usage = []
def wrapper(*args):
if args in cache:
usage.remove(args)
usage.append(args)
return cache[args]
else:
result = func(*args)
cache[args] = result
usage.append(args)
if len(cache) > maxsize:
lru_key = usage.pop(0)
del cache[lru_key]
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator_factory