Group Consecutive Document Tokens
Context
A document-quality tool receives a stream of normalized words from a text file. Repeated neighboring words can indicate emphasis or accidental duplication, so the tool records each uninterrupted stretch as one group while preserving the document’s order.
Problem
Write a function that partitions a list of document tokens into maximal contiguous groups. A group contains consecutive tokens that are all identical. Start a new group whenever the next token differs from the token in the active group. Equal tokens separated by another token must belong to different groups. Return the groups in their original order. If the input list is empty, return an empty list. Each token appears in exactly one returned group.
Examples
tokens = ["read", "read", "carefully", "carefully", "read"][["read", "read"], ["carefully", "carefully"], ["read"]]tokens = ["alpha", "beta", "gamma"][["alpha"], ["beta"], ["gamma"]]tokens = [][]Constraints
0 <= len(tokens) <= 1001 <= len(tokens[i]) <= 20 for every itokens[i]: alphabet lowercasetokens contains only lowercase letters.- Types:
tokensis str[]; result is str[][]
Function signature
def group_document_runs(tokens: list[str]) -> list[list[str]]
tokenslist[str]- The document tokens in reading order.
- returns list[list[str]]
- A list of groups, where each inner list is one maximal uninterrupted run of identical neighboring tokens.
Adapted from MBPP problem task_778 (CC BY 4.0). Rewritten, extended and verified by Iksha.