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 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 % 400 == 0 or (year % 4 == 0 and year % 100 != 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
prev = s[0]
for char in s[1:]:
if char == prev:
count += 1
else:
result.append(prev + str(count))
prev = char
count = 1
result.append(prev + 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 = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
count = 1
result.append(current_char + 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 = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
count = 1
result.append(current_char + 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 = []
chunk = []
for item in items:
chunk.append(item)
if len(chunk) == n:
result.append(chunk)
chunk = []
if chunk:
result.append(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 = []
chunk = []
for item in items:
chunk.append(item)
if len(chunk) == n:
result.append(chunk)
chunk = []
if chunk:
result.append(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 >= 1")
result = []
chunk = []
for item in items:
chunk.append(item)
if len(chunk) == n:
result.append(chunk)
chunk = []
if chunk:
result.append(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:
value = value.strip()
sign = ''
if value.startswith('-'):
sign = '-'
value = value[1:]
elif value.startswith('+'):
value = value[1:]
if '.' in value:
integer_part, fractional_part = value.split('.')
else:
integer_part, fractional_part = value, ''
integer_part = integer_part.lstrip('0')
if integer_part == '':
integer_part = '0'
round_up = False
if digits == 0:
if fractional_part and fractional_part[0] >= '5':
round_up = True
else:
if len(fractional_part) > digits and fractional_part[digits] >= '5':
round_up = True
if round_up:
prefix = integer_part
if digits > 0:
frac_prefix = fractional_part[:digits].ljust(digits, '0')
prefix += frac_prefix
new_prefix = str(int(prefix) + 1)
if digits == 0:
integer_part = new_prefix
fractional_part = ''
else:
if len(new_prefix) <= digits:
integer_part = '0'
fractional_part = new_prefix.zfill(digits)
else:
integer_part = new_prefix[:-digits]
fractional_part = new_prefix[-digits:]
else:
if digits > 0:
fractional_part = fractional_part[:digits].ljust(digits, '0')
else:
fractional_part = ''
is_zero = (integer_part == '0' and (digits == 0 or all(c == '0' for c in fractional_part)))
if is_zero:
sign = ''
if digits == 0:
return sign + integer_part
else:
return sign + 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".
def round_half_up(value: str, digits: int) -> str:
def increment_string(s: str) -> str:
lst = list(s)
i = len(lst) - 1
carry = 1
while i >= 0 and carry:
d = ord(lst[i]) - 48 + carry
carry = d // 10
lst[i] = chr(48 + d % 10)
i -= 1
if carry:
lst.insert(0, '1')
return ''.join(lst)
sign = 1
if value.startswith('-'):
sign = -1
value = value[1:]
elif value.startswith('+'):
value = value[1:]
if '.' in value:
integer_part, fractional_part = value.split('.')
else:
integer_part, fractional_part = value, ''
integer_part = integer_part.lstrip('0') or '0'
if digits == 0:
rounding_digit = fractional_part[0] if fractional_part else '0'
if rounding_digit >= '5':
integer_part = increment_string(integer_part)
result = integer_part
if sign == -1 and result != '0':
result = '-' + result
return result
else:
if len(fractional_part) <= digits:
rounded_fractional = fractional_part.ljust(digits, '0')
result_int = integer_part
else:
rounding_digit = fractional_part[digits]
keep_fractional = fractional_part[:digits]
if rounding_digit >= '5':
combined = integer_part + keep_fractional
incremented = increment_string(combined)
if len(incremented) > len(combined):
new_int = incremented[:-digits]
new_frac = incremented[-digits:]
else:
new_int = incremented[:-digits]
new_frac = incremented[-digits:]
result_int = new_int
rounded_fractional = new_frac
else:
result_int = integer_part
rounded_fractional = keep_fractional
rounded_fractional = rounded_fractional.ljust(digits, '0')
result = result_int + '.' + rounded_fractional
if sign == -1:
if result_int == '0' and all(c == '0' for c in rounded_fractional):
return result
else:
return '-' + result
else:
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, localcontext
def round_half_up(value: str, digits: int) -> str:
with localcontext() as ctx:
ctx.prec = max(len(value) + digits + 10, 100)
d = Decimal(value)
if digits > 0:
quant = Decimal('1e-{}'.format(digits))
else:
quant = Decimal('1')
rounded = d.quantize(quant, 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 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: dict[str, str] = {}
i = 0
n = len(line)
while i < n:
# Skip any whitespace
while i < n and line[i].isspace():
i += 1
if i >= n:
break
# Parse key (up to '=' or whitespace)
key_start = i
while i < n and line[i] != '=' and not line[i].isspace():
i += 1
if i >= n or line[i] != '=':
# Malformed pair; stop parsing
break
key = line[key_start:i]
i += 1 # skip '='
# Parse value
if i < n and line[i] == '"':
# Quoted value
i += 1
val_start = i
while i < n and line[i] != '"':
i += 1
value = line[val_start:i]
if i < n and line[i] == '"':
i += 1 # skip closing quote
else:
# Unquoted value (until whitespace or end)
val_start = i
while i < n and not line[i].isspace():
i += 1
value = line[val_start:i]
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]:
result = {}
i = 0
n = len(line)
while i < n:
while i < n and line[i].isspace():
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=' and not line[i].isspace():
i += 1
key = line[key_start:i]
if i >= n or line[i] != '=':
break
i += 1
if i < n and line[i] == '"':
i += 1
val_start = i
while i < n and line[i] != '"':
i += 1
value = line[val_start:i]
if i < n and line[i] == '"':
i += 1
else:
val_start = i
while i < n and not line[i].isspace():
i += 1
value = line[val_start:i]
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]:
result = {}
i = 0
n = len(line)
while i < n:
while i < n and line[i].isspace():
i += 1
if i >= n:
break
key_start = i
while i < n and line[i] != '=' and not line[i].isspace():
i += 1
key = line[key_start:i]
if i < n and line[i] == '=':
i += 1
else:
result[key] = ''
continue
if i < n and line[i] == '"':
i += 1
val_start = i
while i < n and line[i] != '"':
i += 1
value = line[val_start:i]
if i < n and line[i] == '"':
i += 1
else:
val_start = i
while i < n and not line[i].isspace():
i += 1
value = line[val_start:i]
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], x[1]))
merged = [sorted_intervals[0]]
for start, end in sorted_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 []
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end:
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.
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 = []
current_start, current_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= current_end:
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:
year = d.year
month = d.month + months
# Normalize year and month
year += (month - 1) // 12
month = (month - 1) % 12 + 1
# Determine last day of target month
last_day = calendar.monthrange(year, month)[1]
day = min(d.day, last_day)
return datetime.date(year, month, 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_months = d.year * 12 + d.month - 1 + months
new_year = total_months // 12
new_month = total_months % 12 + 1
try:
return datetime.date(new_year, new_month, d.day)
except ValueError:
last_day = calendar.monthrange(new_year, new_month)[1]
return datetime.date(new_year, new_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
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
year = d.year
month = d.month + months
year += (month - 1) // 12
month = (month - 1) % 12 + 1
last_day = calendar.monthrange(year, month)[1]
day = min(d.day, last_day)
return datetime.date(year, month, 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]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
words_lower = [w.lower() for w in words]
counts = Counter(words_lower)
sorted_items = sorted(counts.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 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]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
words = [w.lower() for w in words]
counts = Counter(words)
sorted_items = sorted(counts.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 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]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
words_lower = [w.lower() for w in words]
counts = Counter(words_lower)
sorted_items = sorted(counts.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:
result = {}
def _flatten(val, prefix):
if isinstance(val, dict):
if not val:
result[prefix] = {}
else:
for k, v in val.items():
_flatten(v, f"{prefix}{sep}{k}")
elif isinstance(val, list):
if not val:
result[prefix] = []
else:
for i, v in enumerate(val):
_flatten(v, f"{prefix}{sep}{i}")
else:
result[prefix] = val
for key, value in obj.items():
_flatten(value, 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:
result = {}
def _flatten(prefix: str, value):
if isinstance(value, dict):
if not value:
result[prefix] = value
else:
for k, v in value.items():
_flatten(f"{prefix}{sep}{k}", v)
elif isinstance(value, list):
if not value:
result[prefix] = value
else:
for i, v in enumerate(value):
_flatten(f"{prefix}{sep}{i}", v)
else:
result[prefix] = value
for k, v in obj.items():
_flatten(str(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 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 helper(prefix: str, value):
if isinstance(value, dict):
if not value:
result[prefix] = {}
else:
for k, v in value.items():
new_prefix = prefix + sep + str(k)
helper(new_prefix, v)
elif isinstance(value, list):
if not value:
result[prefix] = []
else:
for i, v in enumerate(value):
new_prefix = prefix + sep + str(i)
helper(new_prefix, v)
else:
result[prefix] = value
for k, v in obj.items():
helper(str(k), v)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
from collections import OrderedDict
from functools import wraps
from typing import Any, Callable
def lru(maxsize: int):
def decorator(func: Callable[..., Any]):
cache: OrderedDict[tuple, Any] = OrderedDict()
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if maxsize <= 0:
return func(*args, **kwargs)
key = args
if key in cache:
value = cache.pop(key)
cache[key] = value
return value
value = func(*args, **kwargs)
if len(cache) >= maxsize:
cache.popitem(last=False)
cache[key] = value
return value
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
from functools import wraps
from typing import Callable, Any
def lru(maxsize: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
cache: OrderedDict[tuple, Any] = OrderedDict()
@wraps(func)
def wrapper(*args: Any) -> Any:
if args in cache:
result = cache[args]
cache.move_to_end(args)
return result
result = func(*args)
if maxsize > 0:
cache[args] = result
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__.
from collections import OrderedDict
from functools import wraps
def lru(maxsize: int):
def decorator(func):
if maxsize <= 0:
@wraps(func)
def wrapper(*args):
return func(*args)
return wrapper
cache = OrderedDict()
@wraps(func)
def wrapper(*args):
if args in cache:
cache.move_to_end(args)
return cache[args]
result = func(*args)
cache[args] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
return wrapper
return decorator