Compute TF-IDF Scores
Problem statement
Compute the TF-IDF score of term in each document, in input order. Documents are already normalized into lowercase words separated by single spaces; match whole words exactly.
TFis the number of occurrences of term in a document divided by that document's word count.dfis the number of documents containing term at least once.- If
df > 0, useIDF = ln(N / df), where N is the number of documents and ln is the natural logarithm. Do not add smoothing. - The score is
TF * IDF. An empty document scores zero. If df is zero, every score is zero.
Return an empty array for an empty corpus. Floating-point answers use a relative-or-absolute tolerance of 10^-6.
Function
tfIdf(documents: String[], term: String) → double[]Examples
Example 1
documents = ["cat cat dog","dog"]term = "cat"return = [0.46209812037329684,0.0]There are 2 documents and cat appears in 1, so IDF is ln(2). Its term frequency in the first document is 2/3 and in the second is 0.
Example 2
documents = ["cat","cat dog"]term = "cat"return = [0.0,0.0]The term appears in every document, so IDF is ln(1) = 0.
Constraints
- 0 <= documents.length <= 100
- 0 <= documents[i].length <= 2000
- 1 <= term.length <= 20
- Each document is empty or contains lowercase English words separated by exactly one space, without leading or trailing spaces. Each word and term contains 1 to 20 lowercase English letters.