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 % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 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 % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 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 % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 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 = []
n = len(s)
i = 0
while i < n:
char = s[i]
count = 0
while i < n and s[i] == char:
count += 1
i += 1
result.append(f"{char}{count}")
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write rle(s: str) -> str to perform run-length encoding on s. Replace each run of consecutive identical characters with that character followed by the run length. rle("aaabcc") returns "a3b1c2" and rle("") returns "".
def rle(s: str) -> str:
if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(f"{s[i-1]}{count}")
count = 1
result.append(f"{s[-1]}{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 = []
n = len(s)
i = 0
while i < n:
char = s[i]
count = 0
while i < n and s[i] == char:
count += 1
i += 1
result.append(f"{char}{count}")
return "".join(result)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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 = []
iterator = iter(items)
while True:
chunk = []
try:
for _ in range(n):
chunk.append(next(iterator))
result.append(chunk)
except StopIteration:
if chunk:
result.append(chunk)
break
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")
iterator = iter(items)
result = []
while True:
chunk = []
try:
for _ in range(n):
chunk.append(next(iterator))
result.append(chunk)
except StopIteration:
if chunk:
result.append(chunk)
break
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
precision = Decimal("1") if digits == 0 else Decimal("10") ** -digits
rounded = d.quantize(precision, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Format to ensure exact number of decimal places
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 round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
precision = Decimal("1") if digits == 0 else Decimal("10") ** -digits
rounded = d.quantize(precision, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Ensure the string has exactly 'digits' decimal places
# format specifier 'f' avoids scientific notation
format_str = "{:." + str(digits) + "f}"
return format_str.format(rounded)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
precision = Decimal('1') if digits == 0 else Decimal('10') ** -digits
rounded = d.quantize(precision, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Ensure the string format has exactly the requested number of decimal places
# Using format specifier to avoid scientific notation and force precision
fmt = f"{{:.{digits}f}}"
return fmt.format(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 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]:
if not line.strip():
return {}
# Regex explanation:
# (\S+) : Key (one or more non-whitespace characters)
# = : Separator
# ( : Start value group
# "[^"]*" : Either a double-quoted string
# | : OR
# \S* : Zero or more non-whitespace characters (for unquoted/empty)
# ) : End value group
pattern = r'(\S+)=("[^"]*"|\S*)'
matches = re.findall(pattern, line)
result = {}
for key, value in matches:
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]:
if not line.strip():
return {}
# Regex explanation:
# (\S+) matches the key (non-whitespace characters)
# = matches the equals sign
# (?: "([^"]*)" | (\S*) ) matches either:
# 1. A double-quoted string (capturing content inside quotes)
# 2. A sequence of non-whitespace characters (capturing the value)
pattern = r'(\S+)=(?:"([^"]*)"|(\S*))'
matches = re.findall(pattern, line)
result = {}
for key, quoted_val, unquoted_val in matches:
# If the second group matched, it was a quoted value
# If the third group matched, it was an unquoted value
val = quoted_val if quoted_val != "" or f'"{quoted_val}"' in line[line.find(key):] else unquoted_val
# Re-evaluating logic to ensure empty quotes "" are handled vs empty unquoted
# The regex findall returns empty strings for non-matching groups.
# We need to distinguish between a quoted empty string "" and an unquoted empty string.
# Let's use a more robust approach with finditer to check the actual match structure.
pass
# Refined approach using finditer to handle the empty/quoted distinction correctly
result = {}
# This pattern captures the key, the equals, and then either a quoted part or everything until next space
pattern = r'(\S+)=(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
if match.group(2) is not None:
# It was a quoted match (even if empty "")
value = match.group(2)
else:
# It was an unquoted match
value = match.group(3)
result[key] = value
return result
# Correcting the logic for the specific regex behavior in Python
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Match key, then =, then either "quoted" or non-space chars
# Group 1: key, Group 2: quoted content, Group 3: unquoted content
pattern = r'(\S+)=(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# If group 2 is not None, the regex matched the "..." part
# In re.finditer, if a group didn't participate, it is None
if match.group(2) is not None:
value = match.group(2)
else:
value = match.group(3)
result[key] = value
return result
Wait, the regex above has a slight flaw regarding how re handles non-participating groups. Let's provide the clean, working version.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Pattern: Key, =, then ( "quoted" OR non-whitespace )
# We use a non-capturing group for the OR to keep group numbering clean
pattern = r'(\S+)=(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# If group 2 is not None, it means the "..." branch was taken
if match.group(2) is not None:
value = match.group(2)
else:
value = match.group(3)
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]:
if not line.strip():
return {}
# Regex explanation:
# ([^=\s]+) : Key (one or more characters that aren't '=' or whitespace)
# = : The separator
# ( : Start value group
# "([^"]*)" : EITHER a double-quoted string (capturing content inside)
# | : OR
# ([^\s]*) : A sequence of non-whitespace characters (for unquoted values)
# ) : End value group
pattern = r'([^=\s]+)=("([^"]*)"|([^\s]*))'
matches = re.findall(pattern, line)
result = {}
for match in matches:
key = match[0]
# match[2] is the content inside quotes if it matched the first part of the OR
# match[3] is the unquoted value if it matched the second part of the OR
value = match[2] if match[2] != '' or f'"{match[2]}"' in line[line.find(key):] else match[3]
# Re-evaluating logic for empty quotes vs empty unquoted:
# Because re.findall with groups can be tricky with empty matches,
# we check which group actually captured the value.
# If match[2] is the group for quotes, it might be empty string if "" was provided.
# We use the index of the match to be certain.
# Let's refine the value extraction:
# Group 0: Key
# Group 2: Quoted content
# Group 3: Unquoted content
# If the match was a quoted string, the regex engine puts it in group 2.
# If it was unquoted, it puts it in group 3.
# However, if the string was "", group 2 is "" and group 3 is "".
# We can check the raw string or use a more robust approach.
pass
# Re-implementing with a more reliable manual scan or refined regex
result = {}
# This regex finds the key and then looks ahead to see if the value is quoted
# Key = ([^=\s]+)
# Value = ("[^"]*"|[^\s]*)
pattern = r'([^=\s]+)=("(?P<q>[^"]*)"|(?P<u>[^\s]*))'
for m in re.finditer(pattern, line):
key = m.group(1)
if m.group('q') is not None:
value = m.group('q')
else:
value = m.group('u')
result[key] = value
return result
Wait, the logic above has a slight flaw in how re.finditer handles the groups. Let's provide the clean, correct version.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Pattern:
# 1. Key: non-whitespace, non-equals
# 2. Equals sign
# 3. Value: either "quoted content" OR non-whitespace characters
pattern = r'([^=\s]+)=("([^"]*)"|([^\s]*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# group(3) is the content inside quotes
# group(4) is the unquoted value
if match.group(3) is not None:
value = match.group(3)
else:
value = match.group(4)
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 = []
current_start, current_end = sorted_intervals[0]
for next_start, next_end in sorted_intervals[1:]:
if next_start <= current_end:
current_end = max(current_end, next_end)
else:
merged.append((current_start, current_end))
current_start, current_end = next_start, next_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 = []
for current in sorted_intervals:
if not merged:
merged.append(current)
else:
last_start, last_end = merged[-1]
curr_start, curr_end = current
if curr_start <= last_end:
merged[-1] = (last_start, max(last_end, curr_end))
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 = []
for current in sorted_intervals:
if not merged:
merged.append(current)
else:
last_start, last_end = merged[-1]
curr_start, curr_end = current
if curr_start <= last_end:
merged[-1] = (last_start, max(last_end, curr_end))
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 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
last_day_of_new_month = calendar.monthrange(new_year, new_month)[1]
new_day = min(d.day, last_day_of_new_month)
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_months = d.year * 12 + (d.month - 1) + months
new_year = total_months // 12
new_month = (total_months % 12) + 1
last_day_of_new_month = calendar.monthrange(new_year, new_month)[1]
new_day = min(d.day, last_day_of_new_month)
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_months = d.year * 12 + (d.month - 1) + months
new_year = total_months // 12
new_month = (total_months % 12) + 1
last_day_of_new_month = calendar.monthrange(new_year, new_month)[1]
new_day = min(d.day, last_day_of_new_month)
return datetime.date(new_year, new_month, new_day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
import re
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = Counter(word.lower() for word in words)
# Sort by frequency descending, then by word ascending
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]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = Counter(word.lower() for word in words)
# Sort by count descending, then by word ascending
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]]:
words = re.findall(r"[a-zA-Z']+", text)
counts = Counter(word.lower() for word in words)
# Sort by frequency descending, then by word ascending
sorted_words = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return sorted_words[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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(current: any, path: list[str]):
if isinstance(current, dict) and current:
for k, v in current.items():
_recurse(v, path + [str(k)])
elif isinstance(current, list) and current:
for i, v in enumerate(current):
_recurse(v, path + [str(i)])
else:
if not path:
result[current] = current # Should not happen based on signature
return
result[sep.join(path)] = current
# Special case for empty dict/list at top level or nested
# The requirement: "Keep an empty dict or empty list as the value at its key"
def _process(item, prefix):
if isinstance(item, dict) and item:
for k, v in item.items():
new_key = f"{prefix}{sep}{k}" if prefix else k
_process(v, new_key)
elif isinstance(item, list) and item:
for i, v in enumerate(item):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
_process(v, new_key)
else:
# This handles the leaf nodes, including empty dicts/lists
result[prefix] = item
for k, v in obj.items():
_process(v, k)
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(current, prefix):
if isinstance(current, dict):
if not current:
result[prefix] = {}
return
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
_recurse(v, new_key)
elif isinstance(current, list):
if not current:
result[prefix] = []
return
for i, v in enumerate(current):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
_recurse(v, new_key)
else:
result[prefix] = current
for k, v in obj.items():
_recurse(v, str(k))
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(current, prefix):
if isinstance(current, dict) and current:
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
_recurse(v, new_key)
elif isinstance(current, list) and current:
for i, v in enumerate(current):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
_recurse(v, new_key)
else:
result[prefix] = current
for k, v in obj.items():
_recurse(v, str(k))
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 functools import wraps
from collections import OrderedDict
def lru(maxsize: int):
def decorator(func):
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
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write lru(maxsize: int), a decorator factory that caches a function's results by its positional arguments without using functools.lru_cache or functools.cache. It stores at most maxsize results. When the cache is full, evict the least recently used result. A cache hit counts as a use. The decorated function must preserve its original __name__.
import collections
from functools import wraps
def lru(maxsize: int):
def decorator(func):
cache = collections.OrderedDict()
@wraps(func)
def wrapper(*args):
if 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
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):
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