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 = []
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 = []
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 ""
res = []
n = len(s)
i = 0
while i < n:
char = s[i]
count = 0
while i < n and s[i] == char:
count += 1
i += 1
res.append(f"{char}{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 = []
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 = []
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 = []
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))
# Format to ensure exact decimal places and handle trailing zeros
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)
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 decimal places even if trailing zeros are lost in str conversion
format_str = f"{{:.{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)
exponent = Decimal('1') / (Decimal('10') ** digits)
if digits == 0:
# For 0 digits, we round to integer.
# ROUND_HALF_UP in Decimal rounds towards nearest,
# with ties away from zero.
rounded = d.quantize(Decimal('1'), rounding=ROUND_HALF_UP)
return str(rounded)
else:
rounded = d.quantize(exponent, rounding=ROUND_HALF_UP)
# Ensure the string format has exactly 'digits' decimal places
return format(rounded, f'.{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]:
if not line.strip():
return {}
# Regex explanation:
# (\w+)\s*=\s* -> Match key and '='
# (?: -> Start non-capturing group for value
# "([^"]*)" -> Option 1: Double quoted value (captures content inside)
# | -> OR
# (\S*) -> Option 2: Non-quoted sequence of non-whitespace chars
# )
# Note: The non-quoted part \S* is slightly tricky because it must not
# consume the next key. However, since keys are separated by spaces,
# we look for the next sequence of non-space characters.
# We use a regex to find all occurrences of key=value
# This pattern handles: key="quoted value" OR key=unquoted_value
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
matches = re.findall(pattern, line)
result = {}
for key, quoted_val, unquoted_val in matches:
# If quoted_val is not empty string, it's the one captured
# If quoted_val is empty string, it might be empty quotes "" or just no match
# Because of the way findall works with groups, we check which group matched
if quoted_val or (key + '="' in line or f'="{key}=' in line or True):
# In Python regex, if the group didn't match, it returns empty string.
# We need to distinguish between "" and unquoted.
# Re-evaluating: The regex above is a bit loose. Let's use a more robust approach.
pass
# Refined approach: Use finditer to handle the logic of which group captured
result = {}
# This pattern looks for: key= followed by either "..." or non-space chars
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# group 2 is the quoted content, group 3 is the unquoted content
if match.group(2) is not None:
val = match.group(2)
else:
val = match.group(3) if match.group(3) is not None else ""
result[key] = val
return result
Wait, the regex approach above is slightly flawed for complex edge cases. Let's provide a cleaner version using re.finditer to ensure the correct group is picked.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Pattern: key= then ( "quoted" OR non-space-sequence )
# Group 1: key, Group 2: quoted content, Group 3: unquoted content
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
if match.group(2) is not None:
# The value was inside quotes (even if empty "")
value = match.group(2)
else:
# The value was unquoted
value = match.group(3) if match.group(3) is not None else ""
result[key] = value
return result
Actually, the prompt requires a single block. I will refine it to be a single, robust function.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Regex explains:
# (\w+) -> Key: one or more word characters
# \s*=\s* -> Equals sign with optional surrounding whitespace
# (?: -> Non-capturing group for the value
# "([^"]*)" -> Group 2: content inside double quotes
# | -> OR
# (\S*) -> Group 3: non-whitespace characters (unquoted value)
# )
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# If group 2 is not None, the match was a quoted string
if match.group(2) is not None:
value = match.group(2)
else:
# Otherwise, it's the unquoted group 3
value = match.group(3) if match.group(3) is not None else ""
result[key] = value
return result
Final check on c=: \S* will match an empty string, so c= results in result['c'] = ''. This is correct.
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Pattern captures: 1:key, 2:quoted_val, 3:unquoted_val
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re-finditer(pattern, line): # Error in thought, use re.finditer
pass
# Corrected final version
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
# Pattern: (key) = ( "quoted" OR unquoted_chars )
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
# Group 2 is the content inside quotes.
# If it's not None, the value was quoted.
if match.group(2) is not None:
value = match.group(2)
else:
# Group 3 is the unquoted sequence.
value = match.group(3) if match.group(3) is not None else ""
result[key] = value
return result
Wait, one edge case: c= with \S* might consume characters if I'm not careful, but \S* is non-greedy/stops at space. If the input is c= , \S* is empty. This works.
One detail: \S* will match up to the next whitespace. If the string is a=b c=d, a=b is captured, then c=d is captured.
Final code structure:
import re
def parse_kv(line: str) -> dict[str, str]:
if not line.strip():
return {}
result = {}
pattern = r'(\w+)\s*=\s*(?:"([^"]*)"|(\S*))'
for match in re.finditer(pattern, line):
key = match.group(1)
if match.group(2) is not None:
value = match.group(2)
else:
value = match.group(3) if match.group(3) 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 {}
# Pattern explanation:
# ([a-zA-Z0-9_]+) : Match the key (alphanumeric/underscore)
# = : Match the equals sign
# ( : Start value group
# "[^"]*" : Either a quoted string (including spaces and =)
# | : OR
# [^\s]* : A sequence of non-whitespace characters
# ) : End value group
pattern = r'([a-zA-Z0-9_]+)=("[^"]*"|[^\s]*)'
matches = re.findall(pattern, line)
result = {}
for key, value in matches:
# Remove surrounding quotes if they exist
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 {}
result = {}
# Regex breakdown:
# (\S+)= -> Key followed by '='
# ( -> Start value group
# "([^"]*)" -> Option 1: Double quoted string (captures content inside)
# | -> OR
# (\S*) -> Option 2: Non-whitespace characters (for unquoted)
# )
# Note: The unquoted part \S* is tricky because it might stop at a space,
# but the regex needs to handle the space separation.
# A more robust approach using a regex to find the pattern: key=value
# This pattern looks for key= and then either a quoted string or non-space characters.
pattern = r'(\S+)=("(?:[^"\\]|\\.)*"|\S*)'
matches = re.findall(pattern, line)
for key, value in matches:
if value.startswith('"') and value.endswith('"'):
# Remove the outer quotes
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 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)
continue
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: list[tuple[int, int]] = []
for current in sorted_intervals:
if not merged:
merged.append(current)
continue
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)
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_month = calendar.monthrange(new_year, new_month)
new_day = min(d.day, last_day_of_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
def add_months(d: datetime.date, months: int) -> datetime.date:
year = d.year + (d.month + months - 1) // 12
month = (d.month + months - 1) % 12 + 1
# Determine the last day of the target month
if month == 12:
next_month_date = datetime.date(year + 1, 1, 1)
else:
next_month_date = datetime.date(year, month + 1, 1)
last_day_of_month = (next_month_date - datetime.timedelta(days=1)).day
new_day = min(d.day, last_day_of_month)
return datetime.date(year, 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 count 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 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 item: (-item[1], item[0]))
return sorted_words[:k]
Write Python 3.13 code. Answer with one ```python code block that defines the function described below. Use only the standard library. Do not include explanations, examples, tests, input() calls, or print() calls.
Write top_k_words(text: str, k: int) -> list[tuple[str, int]]. A word is a maximal sequence of ASCII letters and apostrophes. Words compare case-insensitively and are returned in lowercase. Return the k most frequent words as (word, count) tuples, sorted by highest count first, breaking ties alphabetically by word.
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
words = re.findall(r"[a-zA-Z']+", text)
# Normalize to lowercase
words = [word.lower() for word in words]
counts = Counter(words)
# Sort by:
# 1. -count (descending order of frequency)
# 2. word (ascending alphabetical order for ties)
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, 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
# Special case: handle the root object being empty
if not obj and isinstance(obj, dict):
return {}
# We need to handle the top level specially to ensure
# empty dicts/lists at the root aren't lost or incorrectly processed
for k, v in obj.items():
_recurse(v, str(k))
# The requirement says: Keep an empty dict or empty list as the value at its key.
# My recursion logic skips empty containers to reach the 'else' block.
# However, if the 'else' block is hit, it assigns the value.
# Let's refine the logic to handle the "empty" requirement specifically.
result = {}
def _flatten(item, path):
if isinstance(item, dict) and item:
for k, v in item.items():
new_path = f"{path}{sep}{k}" if path else str(k)
_flatten(v, new_path)
elif isinstance(item, list) and item:
for i, v in enumerate(item):
new_path = f"{path}{sep}{i}" if path else str(i)
_flatten(v, new_path)
else:
result[path] = item
for k, v in obj.items():
_flatten(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:
def _recurse(current: any, prefix: str) -> dict:
if isinstance(current, dict) and current:
result = {}
for k, v in current.items():
new_key = f"{prefix}{sep}{k}" if prefix else str(k)
result.update(_recurse(v, new_key))
return result
elif isinstance(current, list) and current:
result = {}
for i, v in enumerate(current):
new_key = f"{prefix}{sep}{i}" if prefix else str(i)
result.update(_recurse(v, new_key))
return result
else:
return {prefix: current}
if not isinstance(obj, dict):
return {}
final_dict = {}
for k, v in obj.items():
if isinstance(v, dict) and not v:
final_dict[k] = {}
elif isinstance(v, list) and not v:
final_dict[k] = []
else:
final_dict.update(_recurse(v, k))
return final_dict
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: str):
if isinstance(current, dict) and current:
for k, v in current.items():
new_path = f"{path}{sep}{k}" if path else k
recurse(v, new_path)
elif isinstance(current, list) and current:
for i, v in enumerate(current):
new_path = f"{path}{sep}{i}" if path else str(i)
recurse(v, new_path)
else:
result[path] = current
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 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
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):
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
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__.
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