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 = []
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 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 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: iter, 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 chunks(items, n: int) -> list[list]. items is an iterable, which may be a generator. Return consecutive lists of n elements, where the last list may be shorter. Raise ValueError when n is less than 1.
def chunks(items, n: int) -> list[list]:
if n < 1:
raise ValueError("n must be at least 1")
result = []
current_chunk = []
for item in items:
current_chunk.append(item)
if len(current_chunk) == n:
result.append(current_chunk)
current_chunk = []
if current_chunk:
result.append(current_chunk)
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
exponent = Decimal('1') / (Decimal('10') ** digits)
rounded = d.quantize(exponent, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Ensure the string format matches the requested precision
# Using format string to handle trailing zeros and fixed precision
return "{:.{}f}".format(rounded, digits)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write round_half_up(value: str, digits: int) -> str. The string value represents a decimal number. Round it to digits decimal places, rounding exact ties away from zero based on the exact value written in value. Return a string with exactly digits decimal places, and omit the decimal point when digits is 0. round_half_up("2.675", 2) returns "2.68".
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(value: str, digits: int) -> str:
d = Decimal(value)
exponent = Decimal('1') / (Decimal('10') ** digits)
rounded = d.quantize(exponent, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Ensure fixed precision formatting
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 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)
exponent = Decimal('10') ** -digits
rounded = d.quantize(exponent, rounding=ROUND_HALF_UP)
if digits == 0:
return str(rounded.to_integral_value(rounding=ROUND_HALF_UP))
# Format to ensure exact decimal places are shown
return f"{rounded:.{digits}f}"
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write parse_kv(line: str) -> dict[str, str]. The string line contains key=value pairs separated by one or more spaces. A value may be enclosed in double quotes; if so, it may contain spaces and =, and the quotes are not included in the parsed value. A value may be empty, as in c=. If a key repeats, use the last value. Return {} for an empty line.
import re
def parse_kv(line: str) -> dict[str, str]:
result = {}
if not line.strip():
return result
# Regex pattern:
# 1. ([a-zA-Z0-9_]+) : Capture the key (alphanumeric/underscore)
# 2. = : The assignment operator
# 3. (?: : Non-capturing group for the value
# "([^"]*)" : Either a double-quoted string (captures content inside)
# | : OR
# (\S*) : A sequence of non-whitespace characters (for unquoted values)
# )
pattern = r'([a-zA-Z0-9_]+)=(?:"([^"]*)"|(\S*))'
matches = re.finditer(pattern, line)
for match in matches:
key = match.group(1)
quoted_val = match.group(2)
unquoted_val = match.group(3)
# If group 2 is not None, it was a quoted string (even if empty "")
# If group 3 is not None, it was an unquoted string
if quoted_val is not None:
value = quoted_val
else:
value = unquoted_val if unquoted_val is not None else ""
result[key] = value
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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=]+) : Group 1 (Key) - one or more characters that are not space or '='
# = : The separator '='
# ( : Start Group 2 (Value)
# "[^"]*" : EITHER a double-quoted string (including spaces and '=')
# | : OR
# [^\s]* : A sequence of non-space characters
# ) : End Group 2
pattern = r'([^\s=]+)=("[^"]*"|[^\s]*)'
matches = re.findall(pattern, line)
result = {}
for key, value in matches:
# Remove surrounding quotes if present
if value.startswith('"') and value.endswith('"') and len(value) >= 2:
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 {}
result = {}
# Regex explanation:
# (\S+) : Match the key (one or more non-whitespace characters)
# = : Match the equals sign
# ( : Start value group
# "[^"]*" : Match a double-quoted string (including potential spaces and =)
# | : OR
# \S* : Match zero or more non-whitespace characters
# ) : End value group
pattern = r'(\S+)=("[^"]*"|\S*)'
matches = re.findall(pattern, line)
for key, value in matches:
if value.startswith('"') and value.endswith('"'):
# Remove the surrounding double quotes
result[key] = value[1:-1]
else:
result[key] = value
return result
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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:
prev_start, prev_end = merged[-1]
curr_start, curr_end = current
if curr_start <= prev_end:
# Overlap or touch detected
new_end = max(prev_end, curr_end)
merged[-1] = (prev_start, new_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(list(current))
else:
last_interval = merged[-1]
# Check if current interval overlaps or touches the last merged interval
if current[0] <= last_interval[1]:
last_interval[1] = max(last_interval[1], current[1])
else:
merged.append(list(current))
return [tuple(i) for i in merged]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]. The input intervals may be in any order. Merge intervals that overlap or touch, so (1, 2) and (2, 3) become (1, 3). Return the merged intervals as tuples sorted by start, and leave the input list unchanged.
def merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged = []
current_start, current_end = sorted_intervals[0]
for i in range(1, len(sorted_intervals)):
next_start, next_end = sorted_intervals[i]
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 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
# Handle the case where total_months calculation results in a negative year
# but the logic above is robust for positive/negative offsets.
# If total_months is negative, // 12 and % 12 still behave correctly in Python.
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
# Get the last day of the target month/year
_, last_day_of_new_month = calendar.monthrange(new_year, new_month)
# Use the original day, or the last day if the day is out of range
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
# Handle potential negative years from floor division/modulo behavior
# though datetime.date.year is always >= 1.
_, last_day = calendar.monthrange(new_year, new_month)
new_day = min(d.day, last_day)
return datetime.date(new_year, new_month, new_day)
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write 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]]:
# Find all maximal sequences of ASCII letters and apostrophes
# Using a regex to capture the pattern defined
words = re.findall(r"[a-zA-Z']+", text)
# Normalize to lowercase
counts = Counter(word.lower() for word in words)
# Sort by count descending (primary), then word ascending (secondary)
# We use -x[1] for count to sort descending while keeping x[0] 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]]:
# Find all maximal sequences of ASCII letters and apostrophes
# [a-zA-Z']+ matches one or more letters or apostrophes
words = re.findall(r"[a-zA-Z']+", text)
# Convert to lowercase and count frequencies
counts = Counter(word.lower() for word in words)
# Sort logic:
# 1. Primary: -count (to get descending order for frequency)
# 2. Secondary: word (to get ascending order for alphabetical tie-breaking)
# Python's sort is stable, but we can use a tuple key for a single pass
# We use -x[1] for descending count and x[0] for ascending word
sorted_items = sorted(counts.items(), key=lambda x: (-x[1], x[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]]:
# Pattern for maximal sequence of ASCII letters and apostrophes
# We use findall to get all non-overlapping matches
words = re.findall(r"[a-zA-Z']+", text)
# Convert to lowercase and count frequencies
counts = Counter(word.lower() for word in words)
# Sort by:
# 1. Count (descending) -> -x[1]
# 2. Word (alphabetical/ascending) -> x[0]
sorted_items = sorted(counts.items(), key=lambda x: (-x[1], x[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:
def _flatten(current: any, prefix: str) -> dict:
result = {}
if isinstance(current, dict) and current:
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else k
if isinstance(v, (dict, list)) and v:
result.update(_flatten(v, new_key))
else:
result[new_key] = v
elif isinstance(current, list) and current:
for i, v in enumerate(current):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
if isinstance(v, (dict, list)) and v:
result.update(_flatten(v, new_key))
else:
result[new_key] = v
else:
# This part handles the base case for recursion,
# though the logic above usually prevents calling this for empty containers.
if prefix:
result[prefix] = current
return result
# Special handling for the initial call to ensure empty dicts/lists are preserved
# if they are at the top level or encountered during recursion.
# The requirements state: "Keep an empty dict or empty list as the value at its key."
final_result = {}
def _recurse(curr: any, path: str):
if isinstance(curr, dict) and curr:
for k, v in curr.items():
new_path = f"{path}{sep}{k}" if path else k
if isinstance(v, (dict, list)) and v:
_recurse(v, new_path)
else:
final_result[new_path] = v
elif isinstance(curr, list) and curr:
for i, v in enumerate(curr):
new_path = f"{path}{sep}{i}" if path else str(i)
if isinstance(v, (dict, list)) and v:
_recurse(v, new_path)
else:
final_result[new_path] = v
elif isinstance(curr, (dict, list)):
# If it's an empty dict or list, we need to handle the key assignment.
# However, the loop above only enters if curr is truthy.
# We need to check if the parent called this on an empty object.
pass
# Redefining logic to satisfy "Keep an empty dict or empty list as the value at its key"
def _traverse(curr: any, path: str):
if isinstance(curr, dict) and curr:
for k, v in curr.items():
new_path = f"{path}{sep}{k}" if path else k
if isinstance(v, (dict, list)) and v:
_traverse(v, new_path)
else:
final_result[new_path] = v
elif isinstance(curr, list) and curr:
for i, v in enumerate(curr):
new_path = f"{path}{sep}{i}" if path else str(i)
if isinstance(v, (dict, list)) and v:
_traverse(v, new_path)
else:
final_result[new_path] = v
else:
# This handles the case where the value itself is an empty dict/list
# or a primitive.
if path:
final_result[path] = curr
# The actual logic to satisfy the specific requirement:
# "Keep an empty dict or empty list as the value at its key."
def _solve(data: any, prefix: str = "") -> dict:
res = {}
if isinstance(data, dict):
for k, v in data.items():
new_key = f"{prefix}{sep}{k}" if prefix else k
if isinstance(v, dict) and v:
res.update(_solve(v, new_key))
elif isinstance(v, list) and v:
res.update(_solve(v, new_key))
else:
res[new_key] = v
elif isinstance(data, list):
for i, v in enumerate(data):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
if isinstance(v, dict) and v:
res.update(_solve(v, new_key))
elif isinstance(v, list) and v:
res.update(_solve(v, new_key))
else:
res[new_key] = v
return res
# The recursive function above handles the nesting.
# To ensure empty dicts/lists are preserved, we must check the type before recursing.
def _final_logic(target: any, path: str) -> dict:
out = {}
if isinstance(target, dict):
for k, v in target.items():
new_key = f"{path}{sep}{k}" if path else k
if isinstance(v, (dict, list)) and v:
out.update(_final_logic(v, new_key))
else:
out[new_key] = v
elif isinstance(target, list):
for i, v in enumerate(target):
new_key = f"{path}{sep}{i}" if path else str(i)
if isinstance(v, (dict, list)) and v:
out.update(_final_logic(v, new_key))
else:
out[new_key] = v
return out
return _final_logic(obj, "")
Wait, the instructions say "one code block". I will provide a cleaner version of the logic.
def flatten(obj: dict, sep: str = ".") -> dict:
def _recurse(current: any, path: str) -> dict:
result = {}
if isinstance(current, dict) and current:
for k, v in current.items():
new_key = f"{path}{sep}{k}" if path else k
if isinstance(v, (dict, list)) and v:
result.update(_recurse(v, new_key))
else:
result[new_key] = v
elif isinstance(current, list) and current:
for i, v in enumerate(current):
new_key = f"{path}{sep}{i}" if path else str(i)
if isinstance(v, (dict, list)) and v:
result.update(_recurse(v, new_key))
else:
result[new_key] = v
return result
# To handle the initial call correctly if obj is empty or has empty top-level items
# The requirement says: "Keep an empty dict or empty list as the value at its key."
# The recursive function above handles this by checking `if v` before recursing.
return _recurse(obj, "")
Actually, looking at the requirement flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
My _recurse logic:
For e: {}: v is {}, which is not (dict and v), so result["e"] = {}. Correct.
For c: [{"d": 2}, 3]:
i=0, v={"d": 2}: v is a dict and truthy. _recurse({"d": 2}, "c.0") called._recurse with {"d": 2} and "c.0": k="d", v=2. v is not dict/list. result["c.0.d"] = 2.i=1, v=3: v is not dict/list. result["c.1"] = 3.The logic is correct.
def flatten(obj: dict, sep: str = ".") -> dict:
def _recurse(current: any, path: str) -> dict:
res = {}
if isinstance(current, dict) and current:
for k, v in current.items():
new_path = f"{path}{sep}{k}" if path else k
if isinstance(v, (dict, list)) and v:
res.update(_recurse(v, new_path))
else:
res[new_path] = v
elif isinstance(current, list) and current:
for i, v in enumerate(current):
new_path = f"{path}{sep}{i}" if path else str(i)
if isinstance(v, (dict, list)) and v:
res.update(_recurse(v, new_path))
else:
res[new_path] = v
return res
return _recurse(obj, "")
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write flatten(obj: dict, sep: str = ".") -> dict. Flatten nested dicts and lists into a single level, joining keys with sep and using list indices as keys. Keep an empty dict or empty list as the value at its key. flatten({"a": {"b": 1}, "c": [{"d": 2}, 3], "e": {}}) returns {"a.b": 1, "c.0.d": 2, "c.1": 3, "e": {}}.
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def _recurse(current_obj, parent_key: str):
if isinstance(current_obj, dict) and current_obj:
for k, v in current_obj.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
_recurse(v, new_key)
elif isinstance(current_obj, list) and current_obj:
for i, v in enumerate(current_obj):
new_key = f"{parent_key}{sep}{i}" if parent_key else str(i)
_recurse(v, new_key)
else:
result[parent_key] = current_obj
for k, v in obj.items():
_recurse(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_obj, prefix: str):
if isinstance(current_obj, dict) and current_obj:
for k, v in current_obj.items():
new_key = f"{prefix}{sep}{k}" if prefix else k
recurse(v, new_key)
elif isinstance(current_obj, list) and current_obj:
for i, v in enumerate(current_obj):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
recurse(v, new_key)
else:
result[prefix] = current_obj
# Handle the case where the root is an empty dict/list or the recursion logic
# The requirements state: "Keep an empty dict or empty list as the value at its key."
# The recursion above handles nested empty structures.
# However, if the root itself is empty, we need to ensure the behavior is consistent.
# Special case: if the input is an empty dict or list, the function should return it?
# The prompt implies the function flattens a dict.
if not obj:
return obj
# To handle the requirement: "Keep an empty dict or empty list as the value at its key"
# We check if the current object is empty before recursing.
def walk(val, path):
if isinstance(val, dict) and not val:
result[path] = {}
elif isinstance(val, list) and not val:
result[path] = []
elif isinstance(val, dict):
for k, v in val.items():
new_path = f"{path}{sep}{k}" if path else k
walk(v, new_path)
elif isinstance(val, list):
for i, v in enumerate(val):
new_path = f"{path}{sep}{i}" if path else str(i)
walk(v, new_path)
else:
result[path] = val
for k, v in obj.items():
walk(v, k)
# If the input was empty, the loop above doesn't run.
# But the prompt implies the input is a dict.
return result
Wait, I should refine the logic to be cleaner and strictly follow the rule: "Keep an empty dict or empty list as the value at its key."
def flatten(obj: dict, sep: str = ".") -> dict:
result = {}
def walk(current_val, path):
if isinstance(current_val, dict) and not current_val:
result[path] = {}
elif isinstance(current_val, list) and not current_val:
result[path] = []
elif isinstance(current_val, dict):
for k, v in current_val.items():
new_path = f"{path}{sep}{k}"
walk(v, new_path)
elif isinstance(current_val, list):
for i, v in enumerate(current_val):
new_path = f"{path}{sep}{i}"
walk(v, new_path)
else:
result[path] = current_val
for k, v in obj.items():
walk(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 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 functools
def lru(maxsize: int):
def decorator(func):
cache = {}
# Using a list to track order: end is most recent, beginning is least recent
order = []
@functools.wraps(func)
def wrapper(*args):
if args in cache:
# Cache hit: move to the end of the order list
order.remove(args)
order.append(args)
return cache[args]
result = func(*args)
if len(cache) >= maxsize:
# Evict the least recently used (the first element in order)
oldest = order.pop(0)
del cache[oldest]
cache[args] = result
order.append(args)
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 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