AI Agents by HandAll problemsAbout

All problems › Python drill · medium · ~5 min

d16 · Truncate on word boundaries

truncation chunking

Solve it in your browser →

d16 · Truncate on word boundaries (~5 min)

Chunking text. Edit drills.py. Standard library only; no model calls, no API key.

def truncate_words(text, max_chars):

Shorten text to at most max_chars characters without splitting a word.

Text that fits is returned unchanged. Otherwise keep as many whole words as fit, drop trailing whitespace and append "..."; the result, "..." included, is at most max_chars long. If even the first word doesn't fit, cut it mid-word instead. Raise ValueError if max_chars < 4.

Failure messages are enough to go on, so leave the tests unread until you submit.

Starter code and hidden tests open in the editor. Nothing to install.