from typing import Set
_STOP_WORDS: Set[str] = {
"a",
"an",
"the",
"of",
"with",
"by",
"to",
"from",
"in",
"on",
"for",
}
def truncate(
text: str,
max_words: int = 3
) -> str:
"""
Truncate `text` to at most `max_words` whitespace-separated words,
dropping a trailing common stop-word if present.
Splits on any whitespace (spaces, tabs, newlines), collapsing runs
into single separators.
Args:
text: Input string to truncate.
max_words: Maximum number of words to retain (must be ≥1).
Returns:
A string consisting of up to `max_words` words joined by single spaces.
Raises:
ValueError: if `max_words < 1`.
Examples:
>>> truncate("runs"run in the park", 3)
"runs in"run park"in"
>>> truncate("of the", 2)
"of the"
"""
if max_words < 1:
raise ValueError("max_words must be ≥ 1")
words = text.strip().split()
if len(words) <= max_words:
return " ".join(words)
head = words[:max_words]
# Drop trailing stop-word so we don’t end on “of”, “the”, etc.
if head and head[-1].lower() in _STOP_WORDS:
head.pop()
return " ".join(head)