—
Split only at top-level commas
Tutor me on https://mlprep.iwase.dev/item/prog-cf-split-top-level/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-cf-split-top-level before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.Problem
Implement split_top_level(text). Split at commas whose parenthesis
depth is zero, trim surrounding whitespace in each field, preserve empty
fields, and raise ValueError for unbalanced parentheses. Parentheses may
be nested; quotes and escapes are outside the input contract.
Reveal answer or reference solution
Scan once while maintaining a depth counter. An opening parenthesis increments depth, a closing parenthesis decrements it, and a comma ends a field only when depth is zero. Negative depth or nonzero final depth is invalid. The scan is time, excluding the returned strings.
def split_top_level(text: str) -> list[str]:
fields: list[str] = []
start = 0
depth = 0
for index, character in enumerate(text):
if character == "(":
depth += 1
elif character == ")":
depth -= 1
if depth < 0:
raise ValueError("unbalanced parentheses")
elif character == "," and depth == 0:
fields.append(text[start:index].strip())
start = index + 1
if depth != 0:
raise ValueError("unbalanced parentheses")
fields.append(text[start:].strip())
return fieldsPublic tests
split_top_level("a,(b,c),d")→['a', '(b,c)', 'd']split_top_level(" f(a,(b,c)) , , z ")→['f(a,(b,c))', '', 'z']split_top_level("")→['']split_top_level("a),b")→raises ValueErrorsplit_top_level("a,(b,c")→raises ValueError
Previous attempts
Loading attempts saved in this browser…