—
Summarize consecutive character runs
Tutor me on https://mlprep.iwase.dev/item/prog-cf-summarize-runs/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-cf-summarize-runs 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 summarize_runs(text), which returns (character, count) for
each maximal consecutive run. For example, "aaabbcaa" becomes
[("a", 3), ("b", 2), ("c", 1), ("a", 2)]. Return an empty list for
an empty string.
Reveal answer or reference solution
Keep the current character and count. When the next character differs, emit the completed run and reset the state. Emit the final run after the loop. The algorithm takes time, auxiliary space, and output space for runs.
def summarize_runs(text: str) -> list[tuple[str, int]]:
if text == "":
return []
runs: list[tuple[str, int]] = []
current = text[0]
count = 1
for index in range(1, len(text)):
character = text[index]
if character == current:
count += 1
else:
runs.append((current, count))
current = character
count = 1
runs.append((current, count))
return runsPublic tests
summarize_runs("")→[]summarize_runs("z")→[('z', 1)]summarize_runs("aaabbcaa")→[('a', 3), ('b', 2), ('c', 1), ('a', 2)]summarize_runs("ab")→[('a', 1), ('b', 1)]
Previous attempts
Loading attempts saved in this browser…