PY-32

Find Exact Phrase Starts

  • Medium–Hard
  • Search Indexing
  • Python

Task

Write find_phrase_starts(index, phrase). index has the positional format returned by record_token_positions: each token maps to a dictionary of document IDs, and each document maps to that token's increasing positions. phrase is a sequence of tokens.

Return a dictionary mapping each matching document ID to the zero-based start positions of every exact phrase occurrence. A start is valid when the first phrase token occurs there, the second occurs at the next position, and so on for the whole phrase. Repeated terms in phrase must be checked separately; for example, ['a', 'a'] needs a at both consecutive positions. Omit documents with no match. An empty phrase returns {}.

Preserve document encounter order from index and ascending start-position order within each document. Do not change index, its inner mappings, or any position list.

Example

In d1, "a" at position 0 is followed by "b" at 1, while "a" at position 2 is not. The same consecutive pair begins at 1 in d2.

Your implementation

Edit solution.py and keep this function name and signature:

Return a new dictionary and new result lists. A one-token phrase reports all positions for that token. A phrase containing a token absent from the index has no matching documents. Do not sort document IDs, print the result, or ask for input.