v9.1.1
Menu

Context Window Finder

easyFREEQuestion AnsweringNLP 3: Advanced

Given a document (list of words) and a query word, find the context window of size k around each occurrence of the query word. Return all unique context windows.

Implement find_windows(words, query, k):

  • words: the document as a list of words
  • query: the query word
  • k: window size (number of words on each side)

Output: Return a list of context window strings (each window's words joined by single spaces), in order of first appearance. Matching is case-insensitive. If the query word never appears, return ["No matches found"].

Example

Input
the cat sat on the mat near the door
the
1
Output
the cat
on the mat
near the door
Reasoning
  • words is the document split into n=9n = 9 words, numbered from 0: the(0) cat(1) sat(2) on(3) the(4) mat(5) near(6) the(7) door(8). query is the and k is 1, so a window holds at most 2k+1=32k + 1 = 3 words.
  • The query matches at positions 0, 4 and 7. Around a match at position ii, the window covers positions i−ki - k through i+ki + k, clipped to the valid range 00 to n−1=8n - 1 = 8.
  • Position 0: the range −1-1 to 11 clips to 00 to 11, giving the cat. Only 2 words, since nothing lies left of the first word.
  • Position 4 gives positions 3 to 5, and position 7 gives positions 6 to 8, which ends exactly at the last word.
  • All three windows differ, so all three lines are output in order of appearance: the cat on the mat near the door.
  • Notice that repeats are possible: in "a b a c a" with k=0k = 0 every window is just a, so only one is kept.

Constraints

  • Case-insensitive matching for query word
  • Window extends k words on each side
  • Clip at document boundaries
  • Output unique windows in order of first appearance

Learn this in

More from NLP 3: Advanced

solution.py

Test results

Sign in to run your code against the test cases.