PY-33

Find Nearby Term Positions

  • Medium–Hard
  • Search Indexing
  • Python

Task

Write find_nearby_positions(index, left_term, right_term, max_distance). index has the positional format returned by record_token_positions. max_distance is a positive integer.

For each document, return every pair (left_position, right_position) where left_term occurs at left_position, right_term occurs at right_position, the right position is strictly after the left position, and

right_position - left_position <= max_distance

The two terms may be the same, but a position cannot be paired with itself. Omit documents with no matching pairs. Preserve document encounter order, and within each document order pairs by increasing left position and then increasing right position. Do not change index or any position list.

Example

The pair in d1 is within distance 2; the "red" at position 4 is not before the "blue" at position 2, so it cannot produce a pair. In d2, the distance is 1.

Your implementation

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

Return a new dictionary whose values are new lists of two-item tuples. A term absent from a document contributes no pair, and an empty index returns {}. Do not sort document IDs, print the result, or ask for input.