def computeOverlap(L1, L2): d1, d2 = {}, {} for e in L1: if e not in d1: d1[e] = 1 d1[e] += 1 for e in L2: if e not in d2: d2[e] = 0 d2[e] += 1 o1, o2 = 0, 0 for k in d1: o1 += min(d1[k], d2.get(k,0)) for k in d2: o2 += min(d1.get(k,0), d2[k]) print((100*o1) if o1 else 0 "% of the first list overlaps with the second list") print((100*o2) if o2 else 0 "% of the second list overlaps with the first list")
Of course, you could just do it with defaultdict and a counter to make things a little easier:
from collections import defaultdict, Counter def computeOverlap(L1, L2): d1 = defaultdict(int, Counter(L1)) d2 = defaultdict(int, Counter(L2)) o1, o2 = 0, 0 for k in d1: o1 += min(d1[k], d2[k]) for k in d2: o2 += min(d1[k,0], d2[k]) print((100*o1) if o1 else 0 "% of the first list overlaps with the second list") print((100*o2) if o2 else 0 "% of the second list overlaps with the first list")
source share