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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Jaccard similarity divides the size of the intersection by the size of the union to score set overlap.
- 2Normalizing inputs — stripping and lowercasing — before comparison prevents cosmetic differences from lowering the score.
- 3Combining a lazy generator with max's key and default cleanly finds the best match while handling the empty case.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/ranking-tag-sets-by-jaccard-similarity-explained-python-b6ae/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.