PIXELBANKv9.1.0
Menu

Compute TF-IDF scores for terms across documents.

For each term in each document:

  • TF (Term Frequency): count of term in doctotal terms in doc\frac{\text{count of term in doc}}{\text{total terms in doc}}
  • IDF (Inverse Document Frequency): ln⁡Nnumber of docs containing term\ln\frac{N}{\text{number of docs containing term}}
  • TF-IDF = TF × IDF

where NN is the total number of documents and ln⁡\ln is the natural logarithm.

Return the vocabulary (sorted) and the TF-IDF matrix, rounded to 4 decimal places.

Example:

Input:
documents = ["the cat", "the dog", "the bird"]
Output:
(['bird', 'cat', 'dog', 'the'], [[0.0, 0.5493, 0.0, 0.0], [0.0, 0.0, 0.5493, 0.0], [0.5493, 0.0, 0.0, 0.0]])
Reasoning:
  • First, we calculate the Term Frequency (TF) for each term in each document: for example, in the first document "the cat", TFcat=12TF_{cat} = \frac{1}{2} and TFthe=12TF_{the} = \frac{1}{2}.
  • Then, we calculate the Inverse Document Frequency (IDF) for each term across all documents: for example, IDFcat=ln⁡31IDF_{cat} = \ln\frac{3}{1}, IDFthe=ln⁡33=0IDF_{the} = \ln\frac{3}{3} = 0.
  • Next, we compute the TF-IDF score for each term in each document by multiplying the TF and IDF values: for example, TF−IDFcat=TFcat×IDFcat=12×ln⁡3TF-IDF_{cat} = TF_{cat} \times IDF_{cat} = \frac{1}{2} \times \ln{3}.
  • The final output is a sorted vocabulary and the TF-IDF matrix, rounded to 4 decimal places, where each row represents a document and each column represents a term in the vocabulary.

Constraints:

  • documents: list of strings (split on spaces, lowercase)
  • Return tuple (vocabulary, tfidf_matrix)
  • tfidf_matrix: 2D list (n_docs x vocab_size)
  • Use natural log (ln), round to 4 decimal places
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.