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 % 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 ""
res = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
res.append(f"{prev}{count}")
prev = ch
count = 1
res.append(f"{prev}{count}")
return "".join(res)
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 ""
res = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
res.append(f"{prev}{count}")
prev = ch
count = 1
res.append(f"{prev}{count}")
return "".join(res)
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 ""
res = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
res.append(f"{prev}{count}")
prev = ch
count = 1
res.append(f"{prev}{count}")
return "".join(res)
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] = []
chunk: list = []
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 at least 1")
result: list[list] = []
chunk: list = []
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:
s = value.strip()
negative = False
if s.startswith('-'):
negative = True
s = s[1:]
elif s.startswith('+'):
s = s[1:]
# exponent handling
low = s.lower()
if 'e' in low:
idx = low.index('e')
mantissa_str = s[:idx]
exp_str = s[idx + 1:]
exponent = int(exp_str) if exp_str else 0
if '.' in mantissa_str:
int_m, frac_m = mantissa_str.split('.', 1)
else:
int_m, frac_m = mantissa_str, ""
combined = int_m + frac_m
len_int_m = len(int_m)
new_pos = len_int_m + exponent
if new_pos <= 0:
int_part = "0"
frac_part = "0" * (-new_pos) + combined
elif new_pos >= len(combined):
int_part = combined + "0" * (new_pos - len(combined))
frac_part = ""
else:
int_part = combined[:new_pos]
frac_part = combined[new_pos:]
if int_part == "":
int_part = "0"
else:
if '.' in s:
int_part, frac_part = s.split('.', 1)
else:
int_part, frac_part = s, ""
if int_part == "":
int_part = "0"
# digits negative -> rounding to the left of decimal point
if digits < 0:
n = -digits
int_norm = int_part.lstrip('0')
if int_norm == "":
int_norm = "0"
L = len(int_norm)
if L <= n:
nxt = int_norm[0] if int_norm else '0'
if nxt >= '5':
result_int = "1" + "0" * n
else:
result_int = "0"
else:
keep = int_norm[:L - n]
nxt = int_norm[L - n]
if nxt >= '5':
carry = 1
lst = list(keep)
for i in range(len(lst) - 1, -1, -1):
if carry == 0:
break
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
if carry:
lst.insert(0, '1')
result_int = ''.join(lst) + "0" * n
else:
result_int = keep + "0" * n
if result_int == "" or result_int.strip('0') == "":
return "0"
result_int = result_int.lstrip('0')
if result_int == "":
result_int = "0"
if result_int == "0":
return "0"
return ("-" if negative else "") + result_int
if digits == 0:
if frac_part == "":
int_result = int_part
else:
nxt = frac_part[0]
if nxt >= '5':
carry = 1
lst = list(int_part) if int_part else ['0']
for i in range(len(lst) - 1, -1, -1):
if carry == 0:
break
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
if carry:
lst.insert(0, '1')
int_result = ''.join(lst)
else:
int_result = int_part
int_stripped = int_result.lstrip('0')
if int_stripped == "":
int_stripped = "0"
if int_stripped == "0":
return "0"
return ("-" if negative else "") + int_stripped
# digits > 0
if len(frac_part) <= digits:
int_result = int_part
frac_result = frac_part + "0" * (digits - len(frac_part))
else:
frac_kept = frac_part[:digits]
nxt = frac_part[digits]
if nxt >= '5':
carry = 1
new_frac = list(frac_kept)
for i in range(len(new_frac) - 1, -1, -1):
if carry == 0:
break
d = (ord(new_frac[i]) - 48) + carry
carry = d // 10
new_frac[i] = chr((d % 10) + 48)
if carry:
lst = list(int_part) if int_part else ['0']
for i in range(len(lst) - 1, -1, -1):
if carry == 0:
break
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
if carry:
lst.insert(0, '1')
int_result = ''.join(lst)
frac_result = ''.join(new_frac)
else:
int_result = int_part
frac_result = ''.join(new_frac)
else:
int_result = int_part
frac_result = frac_kept
int_stripped = int_result.lstrip('0')
if int_stripped == "":
int_stripped = "0"
if int_stripped == "0" and frac_result == "0" * digits:
return "0." + frac_result if digits > 0 else "0"
# for digits>0 we already have frac_result
if int_stripped == "0" and frac_result.strip('0') == "":
# zero case already handled, but keep sign off
if frac_result == "0" * digits:
return "0." + frac_result
prefix = "-" if negative else ""
# re-check zero after stripping (e.g. "-0.00")
if int_stripped == "0" and frac_result == "0" * digits:
prefix = ""
return prefix + int_stripped + "." + frac_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:
def add_one_to_int_str(s: str) -> str:
if s == "":
s = "0"
lst = list(s)
carry = 1
for i in range(len(lst) - 1, -1, -1):
if carry == 0:
break
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
if carry:
lst.insert(0, '1')
return ''.join(lst)
s = value.strip()
sign = 1
if s.startswith('-'):
sign = -1
s = s[1:]
elif s.startswith('+'):
s = s[1:]
low = s.lower()
if 'e' in low:
idx = low.find('e')
mant = s[:idx]
exp_str = s[idx + 1:]
try:
exp = int(exp_str) if exp_str else 0
except:
exp = 0
if '.' in mant:
int_m, frac_m = mant.split('.', 1)
else:
int_m, frac_m = mant, ""
if int_m == "":
int_m = "0"
combined = int_m + frac_m
if combined == "":
combined = "0"
pos = len(int_m) + exp
if pos <= 0:
int_part = "0"
frac_part = "0" * (-pos) + combined
elif pos >= len(combined):
int_part = combined + "0" * (pos - len(combined))
frac_part = ""
else:
int_part = combined[:pos]
frac_part = combined[pos:]
if int_part == "":
int_part = "0"
else:
if '.' in s:
int_part, frac_part = s.split('.', 1)
if int_part == "":
int_part = "0"
else:
int_part = s if s != "" else "0"
frac_part = ""
if int_part == "":
int_part = "0"
n = digits
if n >= 0:
if len(frac_part) <= n:
new_int = int_part
new_frac = frac_part + "0" * (n - len(frac_part)) if n > 0 else ""
stripped_int = new_int.lstrip('0')
if stripped_int == "":
stripped_int = "0"
is_zero = False
if stripped_int == "0":
if n == 0:
is_zero = True
else:
if new_frac.strip('0') == "":
is_zero = True
prefix = "-" if sign == -1 and not is_zero else ""
if n == 0:
return prefix + stripped_int
else:
return prefix + stripped_int + "." + new_frac
else:
kept = frac_part[:n] if n > 0 else ""
first_discarded = frac_part[n]
if first_discarded >= '5':
if n > 0:
carry = 1
new_kept_list = list(kept)
for i in range(n - 1, -1, -1):
if carry == 0:
break
d = (ord(new_kept_list[i]) - 48) + carry
carry = d // 10
new_kept_list[i] = chr((d % 10) + 48)
if carry:
new_int = add_one_to_int_str(int_part)
new_frac = ''.join(new_kept_list)
else:
new_int = int_part
new_frac = ''.join(new_kept_list)
stripped_int = new_int.lstrip('0')
if stripped_int == "":
stripped_int = "0"
is_zero = False
if stripped_int == "0" and (new_frac == "" or new_frac.strip('0') == ""):
is_zero = True
prefix = "-" if sign == -1 and not is_zero else ""
return prefix + stripped_int + "." + new_frac
else:
new_int = add_one_to_int_str(int_part)
stripped_int = new_int.lstrip('0')
if stripped_int == "":
stripped_int = "0"
is_zero = stripped_int == "0"
prefix = "-" if sign == -1 and not is_zero else ""
return prefix + stripped_int
else:
new_int = int_part
new_frac = kept if n > 0 else ""
stripped_int = new_int.lstrip('0')
if stripped_int == "":
stripped_int = "0"
is_zero = False
if stripped_int == "0":
if n == 0:
is_zero = True
else:
if new_frac.strip('0') == "":
is_zero = True
prefix = "-" if sign == -1 and not is_zero else ""
if n == 0:
return prefix + stripped_int
else:
return prefix + stripped_int + "." + new_frac
else:
k = -n
stripped = int_part.lstrip('0')
if stripped == "":
stripped = "0"
L = len(stripped)
if L <= k:
if L == k:
first_discarded = stripped[0]
else:
first_discarded = '0'
if first_discarded >= '5':
result_int = "1" + "0" * k
prefix = "-" if sign == -1 else ""
return prefix + result_int
else:
return "0"
else:
keep_len = L - k
kept_part = stripped[:keep_len]
first_discarded = stripped[keep_len]
if first_discarded >= '5':
new_kept = add_one_to_int_str(kept_part)
result_int = new_kept + "0" * k
prefix = "-" if sign == -1 else ""
return prefix + result_int
else:
result_int = kept_part + "0" * k
if result_int.strip('0') == "":
return "0"
prefix = "-" if sign == -1 else ""
return prefix + result_int
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, getcontext
def round_half_up(value: str, digits: int) -> str:
s0 = value.strip()
if "e" in s0.lower():
getcontext().prec = max(28, len(s0) + abs(digits) + 10)
d = Decimal(s0)
exp = Decimal(1).scaleb(-digits)
dq = d.quantize(exp, rounding=ROUND_HALF_UP)
if dq == 0:
dq = abs(dq)
return format(dq, "f")
s = s0
sign = 1
if s.startswith("-"):
sign = -1
s = s[1:]
elif s.startswith("+"):
s = s[1:]
if "." in s:
int_part_str, frac_part_str = s.split(".", 1)
else:
int_part_str, frac_part_str = s, ""
if int_part_str == "":
int_part_str = "0"
int_part_norm = int_part_str.lstrip("0")
if int_part_norm == "":
int_part_norm = "0"
def _inc_str(t: str) -> str:
if t == "":
return "1"
t = t.lstrip("0")
if t == "":
t = "0"
lst = list(t)
i = len(lst) - 1
carry = 1
while i >= 0 and carry:
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
i -= 1
if carry:
lst.insert(0, "1")
return "".join(lst)
if digits >= 0:
if digits >= len(frac_part_str):
new_int = int_part_norm
new_frac = frac_part_str + "0" * (digits - len(frac_part_str))
else:
kept_frac = frac_part_str[:digits]
rounding_digit = frac_part_str[digits]
if rounding_digit >= "5":
if digits == 0:
new_int = _inc_str(int_part_norm)
new_frac = ""
else:
lst = list(kept_frac)
carry = 1
for i in range(digits - 1, -1, -1):
d = (ord(lst[i]) - 48) + carry
carry = d // 10
lst[i] = chr((d % 10) + 48)
if carry == 0:
break
new_frac = "".join(lst)
if carry:
new_int = _inc_str(int_part_norm)
else:
new_int = int_part_norm
else:
new_int = int_part_norm
if digits == 0:
new_frac = ""
else:
new_frac = kept_frac
is_zero = new_int == "0" and (digits == 0 or new_frac == "0" * digits)
if is_zero:
sign = 1
if digits == 0:
res = new_int
else:
res = new_int + "." + new_frac
if sign == -1:
res = "-" + res
return res
else:
n = -digits
L = len(int_part_norm)
keep_len = L + digits
combined = int_part_norm + frac_part_str
if keep_len < 0:
return "0"
kept = combined[:keep_len] if keep_len > 0 else ""
rounding_digit = combined[keep_len] if keep_len < len(combined) else "0"
round_up = rounding_digit >= "5"
if round_up:
if kept == "":
inc_kept = "1"
else:
inc_kept = _inc_str(kept)
new_int = inc_kept + "0" * n
else:
if kept == "":
new_int = "0"
else:
new_int = kept + "0" * n
new_int_norm = new_int.lstrip("0")
if new_int_norm == "":
return "0"
if sign == -1:
return "-" + new_int_norm
return new_int_norm
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
def parse_kv(line: str) -> dict[str, str]:
if not line or not line.strip():
return {}
res: dict[str, str] = {}
n = len(line)
i = 0
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
if i >= n or line[i] != '=':
continue
key = line[key_start:i]
i += 1
if i < n and line[i] == '"':
i += 1
end = line.find('"', i)
if end == -1:
value = line[i:]
i = n
else:
value = line[i:end]
i = end + 1
else:
val_start = i
while i < n and not line[i].isspace():
i += 1
value = line[val_start:i]
res[key] = value
return res
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] = {}
n = len(line)
i = 0
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
if i >= n or line[i] != '=':
while i < n and not line[i].isspace():
i += 1
continue
key = line[key_start:i]
i += 1
if i < n and line[i] == '"':
i += 1
end = line.find('"', i)
if end == -1:
value = line[i:]
i = n
else:
value = line[i:end]
i = end + 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]:
if not line or not line.strip():
return {}
result: dict[str, str] = {}
n = len(line)
i = 0
while i < n:
while i < n and line[i].isspace():
i += 1
if i >= n:
break
start_key = i
while i < n and line[i] != '=' and not line[i].isspace():
i += 1
if i >= n or line[i] != '=':
while i < n and not line[i].isspace():
i += 1
continue
key = line[start_key:i]
i += 1
if i < n and line[i] == '"':
i += 1
end = line.find('"', i)
if end == -1:
value = line[i:]
i = n
else:
value = line[i:end]
i = end + 1
result[key] = value
else:
start_val = i
while i < n and not line[i].isspace():
i += 1
value = line[start_val: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])
merged: list[tuple[int, int]] = []
cur_start, cur_end = sorted_intervals[0]
for start, end in sorted_intervals[1:]:
if start <= cur_end:
if end > cur_end:
cur_end = end
else:
merged.append((cur_start, cur_end))
cur_start, cur_end = start, end
merged.append((cur_start, cur_end))
return merged
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]. The input intervals may be in any order. Merge intervals that overlap or touch, so (1, 2) and (2, 3) become (1, 3). Return the merged intervals as tuples sorted by start, and leave the input list unchanged.
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged = [sorted_intervals[0]]
for start, end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, last_end if last_end > end else 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 = [sorted_intervals[0]]
for start, end in sorted_intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end:
merged[-1] = (last_start, last_end if last_end > end else 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
import calendar
def add_months(d: datetime.date, months: int) -> datetime.date:
total_months = d.month - 1 + months
year = d.year + total_months // 12
month = total_months % 12 + 1
last_day = calendar.monthrange(year, month)[1]
day = d.day if d.day <= last_day else 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
def add_months(d: datetime.date, months: int) -> datetime.date:
total = d.year * 12 + (d.month - 1) + months
new_year, new_month0 = divmod(total, 12)
new_month = new_month0 + 1
if new_month == 2:
is_leap = new_year % 4 == 0 and (new_year % 100 != 0 or new_year % 400 == 0)
dim = 29 if is_leap else 28
elif new_month in (4, 6, 9, 11):
dim = 30
else:
dim = 31
new_day = d.day if d.day <= dim else dim
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 = d.year * 12 + (d.month - 1) + months
year, month0 = divmod(total, 12)
month = month0 + 1
dim = calendar.monthrange(year, month)[1]
day = d.day if d.day <= dim else dim
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)
lowered = [w.lower() for w in words]
counts = Counter(lowered)
sorted_words = sorted(counts.items(), key=lambda x: (-x[1], x[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
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
if k <= 0:
return []
words = [w.lower() for w in re.findall(r"[A-Za-z']+", text)]
if not words:
return []
counts = Counter(words)
sorted_words = sorted(counts.items(), key=lambda x: (-x[1], x[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
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
if k <= 0:
return []
words = re.findall(r"[A-Za-z']+", text)
lowered = [w.lower() for w in words]
counts = Counter(lowered)
sorted_words = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
return sorted_words[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write flatten(obj: dict, sep: str = ".") -> dict. Flatten nested dicts and lists into a single level, joining keys with sep and using list indices as keys. Keep an empty dict or empty list as the value at its key. flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def _helper(cur, prefix):
if isinstance(cur, dict):
if not cur:
if prefix is not None:
result[prefix] = cur
return
for k, v in cur.items():
new_key = f"{prefix}{sep}{k}" if prefix is not None else str(k)
_helper(v, new_key)
elif isinstance(cur, list):
if not cur:
if prefix is not None:
result[prefix] = cur
return
for i, v in enumerate(cur):
new_key = f"{prefix}{sep}{i}" if prefix is not None else str(i)
_helper(v, new_key)
else:
if prefix is not None:
result[prefix] = cur
_helper(obj, None)
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(cur, prefix: str):
if isinstance(cur, dict):
if not cur:
if prefix:
result[prefix] = {}
return
for k, v in cur.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
if isinstance(v, dict):
if not v:
result[new_key] = {}
else:
_flatten(v, new_key)
elif isinstance(v, list):
if not v:
result[new_key] = []
else:
_flatten(v, new_key)
else:
result[new_key] = v
elif isinstance(cur, list):
if not cur:
if prefix:
result[prefix] = []
return
for i, item in enumerate(cur):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
if isinstance(item, dict):
if not item:
result[new_key] = {}
else:
_flatten(item, new_key)
elif isinstance(item, list):
if not item:
result[new_key] = []
else:
_flatten(item, new_key)
else:
result[new_key] = item
else:
if prefix:
result[prefix] = cur
_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 _recurse(cur, prefix: str):
if isinstance(cur, dict):
if not cur:
if prefix != "":
result[prefix] = cur
return
for k, v in cur.items():
ks = str(k)
new_key = f"{prefix}{sep}{ks}" if prefix else ks
_recurse(v, new_key)
elif isinstance(cur, list):
if not cur:
if prefix != "":
result[prefix] = cur
return
for i, item in enumerate(cur):
ik = str(i)
new_key = f"{prefix}{sep}{ik}" if prefix else ik
_recurse(item, new_key)
else:
result[prefix] = cur
_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 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
def lru(maxsize: int):
def decorator(func):
cache = collections.OrderedDict()
def wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
if maxsize is not None and maxsize > 0:
cache[key] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
from collections import OrderedDict
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
def wrapper(*args, **kwargs):
key = args
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
if len(cache) > maxsize:
cache.popitem(last=False)
return result
wrapper.__name__ = func.__name__
return wrapper
return decorator
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
from collections import OrderedDict
def lru(maxsize: int):
def decorator(func):
cache = OrderedDict()
def wrapper(*args, **kwargs):
if kwargs:
try:
key = args + tuple(sorted(kwargs.items()))
hash(key)
except TypeError:
return func(*args, **kwargs)
else:
key = args
try:
hash(key)
except TypeError:
return func(*args, **kwargs)
if key in cache:
cache.move_to_end(key)
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
if maxsize is not None and len(cache) > maxsize:
cache.popitem(last=False)
return result
wrapper.__name__ = func.__name__
wrapper.__qualname__ = getattr(func, "__qualname__", func.__name__)
wrapper.__doc__ = getattr(func, "__doc__", None)
wrapper.__module__ = getattr(func, "__module__", None)
return wrapper
return decorator