Word-Count Cosine Score for Two Text Strings
Arrays & HashingAuto-graded · 22 test casesLast updated
Compute the cosine of the angle between the word-frequency vectors of two strings, using a hash-map counter and guarding against empty inputs.
Word-Count Cosine Score
You are given two strings, first and second. Turn each one into a vector of word counts, then measure how closely the two vectors point in the same direction.
How to build the vectors
- Split each string on whitespace, so any run of spaces, tabs or newlines separates words, and leading or trailing whitespace is ignored. Python's
str.split()with no arguments does exactly this. - Words are compared exactly as they appear. The comparison is case-sensitive, and punctuation stays part of the word, so
"Cat","cat"and"cat,"are three different words. - Each distinct word is one dimension of the vector. Its value is the number of times the word occurs in that string.
What to compute
The score is:
dot(A, B) / (|A| * |B|)
dot(A, B)is the sum, over every word, of (count infirst) multiplied by (count insecond). A word missing from either string contributes 0.|A|is the square root of the sum of the squared counts offirst.|B|is the same forsecond.
Compute the result as dot / (norm_first * norm_second), with each norm computed separately as a square root. Do not round the result or clamp it, so tiny floating-point differences such as 0.9999999999999998 for identical strings are expected.
Edge case
If either string contains no words (it is empty or only whitespace), return 0.0.
Task
Implement the function that returns this score as a float.
Constraints
firstandsecondare Python strings and may be empty.- Total length of the two strings is at most about 10^5 characters.
- Words are separated by whitespace only. There is no lowercasing and no punctuation stripping.
- The return value is a float between 0 and 1 inclusive, apart from floating-point error.
Examples
Example 1
Input: word_count_cosine('the cat sat on the mat', 'the cat sat on the mat')
Output: 0.9999999999999998
Example 2
Input: word_count_cosine('the cat sat', 'the dog sat')
Output: 0.6666666666666667
Example 3
Input: word_count_cosine('hello world', 'goodbye')
Output: 0
Example 4
Input: word_count_cosine('', 'any text')
Output: 0
Hints
Hint 1
Count how many times each whitespace-separated word appears in each string. A Counter (hash map from word to count) works well.
Hint 2
Only words present in both strings add anything to the dot product, and a Counter returns 0 for a missing key. The norms are square roots of the sums of squared counts.
Hint 3
Check for an empty word list before dividing, because a zero-length vector would cause a division by zero. Return 0.0 in that case.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each string becomes a sparse vector: a dictionary mapping every distinct word to its number of occurrences. The cosine of the angle between two vectors is their dot product divided by the product of their lengths.
- Split each string on whitespace and count the words with a
Counter. - If either counter is empty, return
0.0. A zero vector has no direction and its length would make the denominator zero. - Compute the dot product by walking through the words of the first counter and multiplying each count by the matching count in the second. A
Counterreturns 0 for absent keys without inserting them, so words that appear in only one string add nothing. - Compute each vector's length as the square root of the sum of its squared counts.
- Return
dot / (norm_first * norm_second).
Why it is correct
Any dimension where one vector is 0 adds 0 to the dot product, so summing over the words of one string reproduces the full dot product over the union vocabulary. No explicit shared vocabulary is needed. Counts are non-negative, so the result lies between 0 (no shared words) and 1 (proportional word counts). Dividing by the lengths removes the effect of text length, leaving only the relative word frequencies. The empty-input guard prevents division by zero and gives the required 0.0.
For "the cat sat" and "the dog sat", the vectors share 2 of 3 words and each has length √3. The dot product is 2, so the result is 2/3, about 0.6667.
Complexity
Let n and m be the lengths of the two strings.
- Time: O(n + m). Splitting and counting are linear, and the dot product and norms are linear in the number of distinct words, with O(1) average lookups.
- Space: O(n + m) for the token lists and counters.
Reference solution
from collections import Counter
from math import sqrt
def word_count_cosine(first, second):
# Whitespace-separated, case-sensitive words.
freq_first = Counter(first.split())
freq_second = Counter(second.split())
if not freq_first or not freq_second:
return 0.0
dot = sum(cnt * freq_second[word] for word, cnt in freq_first.items())
norm_first = sqrt(sum(cnt * cnt for cnt in freq_first.values()))
norm_second = sqrt(sum(cnt * cnt for cnt in freq_second.values()))
return dot / (norm_first * norm_second)