Measure how much two sentences overlap.
What to build
A program that prints the shared words and the Jaccard similarity of two lines.
Requirements
- Lowercase each line and turn it into a set of whitespace-separated words.
- Print
shared:and the shared words in alphabetical order separated by spaces, orshared: none. - Print
jaccard: Jwith three decimal places, where J is the size of the intersection divided by the size of the union.
Input
Two lines of text.
Output
Two lines.
Constraints
Each line has at least one word and at most 500 words.
Example
Input:
the cat sat
the cat ran
Output:
shared: cat the
jaccard: 0.500
Why it works
Sets ignore repeats and order, so the ratio of shared words to all words measures overlap on a scale from 0 (nothing shared) to 1 (the same words).
Examples
Example 1 · Input
the cat sat the cat ran
Expected output
shared: cat the jaccard: 0.500
Example 2 · Input
I like tea you love coffee
Expected output
shared: none jaccard: 0.000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
`a & b` is the intersection of two sets and `a | b` their union.
Hint 2
Sort the shared words before printing them.
Solution
Show one correct solution (try it yourself first)
a = set(input().lower().split())
b = set(input().lower().split())
shared = sorted(a & b)
print("shared:", " ".join(shared) if shared else "none")
print(f"jaccard: {len(a & b) / len(a | b):.3f}")