Two businesses are described by lists of attribute strings a and b. Compute their Jaccard similarity: the number of attributes the two businesses share, divided by the number of distinct attributes across both.
For sets A and B the Jaccard similarity is J(A,B)=∣A∪B∣∣A∩B∣.
Treat each input list as a set, so an attribute repeated inside one list counts once. Return the result as a float rounded to 2 decimal places. If both lists are empty, return 0.0.
Function Signature
def jaccard_similarity(a: list[str], b: list[str]) -> float:
Rules
-
Duplicate attributes within a list are ignored.
-
If both lists are empty (the union is empty), return
0.0
.
-
Round half up on the exact ratio: a ratio of exactly 0.125 becomes
0.13
, and 1/3 becomes
0.33
.
Constraints
-
0 <= len(a), len(b) <= 10^4
-
1 <= len(attribute) <= 50
-
Each attribute consists of lowercase English letters, digits and underscores.
Examples
Input: a = ["wifi", "parking", "outdoor_seating", "vegan"], b = ["wifi", "parking", "delivery"]
Output: 0.4
The shared attributes are wifi and parking (2 of them), and the union has 5 distinct attributes: wifi, parking, outdoor_seating, vegan and delivery. The similarity is 2/5 = 0.40.
Input: a = ["coffee", "pastries"], b = ["bar", "live_music"]
Output: 0.0
No attribute appears in both lists, so the intersection is empty and the result is 0/4 = 0.0.
Input: a = ["wifi", "wifi"], b = ["wifi", "parking", "vegan", "delivery", "patio", "bar", "tv", "dog_friendly"]
Output: 0.13
a collapses to the single attribute wifi. The union is the 8 distinct attributes of b, the intersection is {wifi}, and 1/8 = 0.125 rounds half up to 0.13.