python 21 lines · 5 steps

Ranking tag sets by Jaccard similarity

Two functions measure overlap between tag collections and pick the closest match from a set of candidates.

Explained by highlit
1from typing import Iterable
2 
3 
4def jaccard_similarity(tags_a: Iterable[str], tags_b: Iterable[str]) -> float:
5 set_a = {tag.strip().lower() for tag in tags_a if tag.strip()}
6 set_b = {tag.strip().lower() for tag in tags_b if tag.strip()}
7 
8 if not set_a and not set_b:
9 return 1.0
10 
11 intersection = set_a & set_b
12 union = set_a | set_b
13 return len(intersection) / len(union)
14 
15 
16def most_similar(target: Iterable[str], candidates: dict[str, Iterable[str]]) -> tuple[str, float] | None:
17 scored = (
18 (name, jaccard_similarity(target, tags))
19 for name, tags in candidates.items()
20 )
21 return max(scored, key=lambda pair: pair[1], default=None)
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Jaccard similarity divides the size of the intersection by the size of the union to score set overlap.
  2. 2Normalizing inputs — stripping and lowercasing — before comparison prevents cosmetic differences from lowering the score.
  3. 3Combining a lazy generator with max's key and default cleanly finds the best match while handling the empty case.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Ranking tag sets by Jaccard similarity — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code