def jaccard_similarity(
        set_a, set_b, element_to_weight=None, max_intersections=None):
    """Calculates Jaccard similarity, a measure of set overlap.

    Args:
        set_a: First set.
        set_b: Second set.
        element_to_weight: Optional, a dict of set elements to
            numeric weights. This results in a weighted Jaccard
            similarity. Default weight is 1.
        max_intersections: Optional integer, ignore intersections
            beyond this threshold. If elements are weighted, the
            strongest intersections are the ones counted.

    Returns:
        Float, 0 (no overlap) - 1 (complete overlap). Two empty sets
        return 0.
    """
    if element_to_weight is None:
        element_to_weight = {}
    intersection_weights = sorted([
        max(element_to_weight.get(e, 1), 1)
        for e in set_a.intersection(set_b)], reverse=True)
    if max_intersections is not None:
        intersection_weights = intersection_weights[:max_intersections]

    intersection = sum(intersection_weights)
    union = intersection + len(set_a.union(set_b)) - len(intersection_weights)
    if not union:
        return 0.0
    return intersection / float(union)