Command Palette

Search for a command to run...

Hectal
Phase 8: Retrieval Basics (RAG)
LLM Engineering · Exercise 2 of 6 PreviousNext
Intermediate

Rank documents with TF-IDF

Write rank(query, docs) returning the names of the documents with a score above 0, best first. A document's score is the sum, over the query words, of (how many times the word is in the document) times ln(N / df), where N is the number of documents and df is how many documents contain the word. Words no document contains add nothing.

Round each score to 4 decimals before sorting, and break ties alphabetically by name.

What Check tests

  1. rank("red", DOCS) is ["b", "a"] (b says red twice)
  2. Rare words count more: rank("blue bus", DOCS) is ["c", "b"]
  3. A word nobody has gives []
  4. Equal scores are ordered by name
  5. A word in every document scores 0 and is left out

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.