KatInterview

Rank Documents by Query Relevance with Smoothed TF-IDF

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinghashingtf-idftokenization

Last updated

Tests hashing and counting over text: tokenize, compute smoothed IDF for query terms, score every document, and sort by descending score with an index tie-break.

Rank Documents by Query Relevance

You have a collection of text documents and a search query. Score each document against the query using a smoothed TF-IDF formula, then report the document positions from most to least relevant.

Tokenization

Apply the same procedure to every document and to the query:

  1. Convert the text to lowercase.
  2. A token is a maximal run of consecutive Unicode letters or digits. Every other character, including the underscore _, separates tokens.
  3. Empty tokens are never produced.

Scoring

Let N be the number of documents and tokens(x) the token list of a text x (repeats kept).

  • Term frequency: tf(t, d) is the number of times token t occurs in document d.

  • Document frequency: df(t) is the number of documents that contain t at least once.

  • Smoothed inverse document frequency (natural logarithm):

    idf(t) = ln((N + 1) / (df(t) + 1)) + 1

  • Score of a document d for query q: sum over every token t in the query token list, repeats included:

    score(d, q) = Σ tf(t, d) · idf(t)

A query token that occurs twice in the query therefore contributes twice. A query token that appears in no document contributes nothing.

Task

Return a list containing every document index 0 … N-1 exactly once, ordered by score from highest to lowest. If two documents have equal score, the one with the smaller index comes first. Documents with score 0 (including empty documents) are still included, at the end, in index order. If the query has no tokens, every score is 0.

Function

Implement rank_by_tfidf(docs, query), where docs is a list of strings and query is a string. It returns a list of integers.

Constraints

  • 1 <= len(docs) <= 10^4
  • The total number of tokens across all documents is at most about 2 * 10^6
  • Documents and the query may be empty strings or contain punctuation and mixed case
  • Use the natural logarithm and ordinary floating-point arithmetic

Examples

Example 1

Input: rank_by_tfidf(['red apple', 'green apple', 'banana'], 'apple')

Output: [0, 1, 2]

Example 2

Input: rank_by_tfidf(['The quick brown fox', 'quick blue hare', 'slow turtle'], 'quick')

Output: [0, 1, 2]

Example 3

Input: rank_by_tfidf(['cat cat dog', 'dog bird', 'fish'], 'cat dog')

Output: [0, 1, 2]

Example 4

Input: rank_by_tfidf(['', 'one two', 'three'], 'missing term')

Output: [0, 1, 2]

Hints

Hint 1

Only tokens that occur in the query can change a score, so you do not need counts for any other word.

Hint 2

Count query tokens with multiplicity first. Then make one pass over the documents, counting only query tokens, and update df once per document for each query term present.

Hint 3

Compute scores in a fixed term order so identical documents get identical floats, then sort indices with the key (-score, index).