Percentage Overlap of Two Lists

OneManRiot picture OneManRiot · Apr 28, 2015 · Viewed 9.2k times · Source

This is more of a math problem than anything else. Lets assume I have two lists of different sizes in Python

listA = ["Alice", "Bob", "Joe"]
listB = ["Joe", "Bob", "Alice", "Ken"]

I want to find out what percentage overlap these two lists have. Order is not important within the lists. Finding overlap is easy, I've seen other posts on how to do that but I can't quite extend it in my mind to finding out what percentage they overlap. If I compared the lists in different orders would the result come out differently? What would be the best way of doing this?

Answer

geckon picture geckon · Apr 28, 2015

From the principal point of view, I'd say that there are two sensible questions you might be asking:

  1. What percentage the overlap is if compared to the first list? I.e. how big is the common part in comparison to the first list?
  2. The same thing for the second list.
  3. What percentage the overlap is if compared to the "universe" (i.e. the union of both lists)?

There can surely be found other meanings as well and there would be many of them. All in all you should probably know what problem you're trying to solve.

From programming point of view, the solution is easy:

listA = ["Alice", "Bob", "Joe"]
listB = ["Joe", "Bob", "Alice", "Ken"]

setA = set(listA)
setB = set(listB)

overlap = setA & setB
universe = setA | setB

result1 = float(len(overlap)) / len(setA) * 100
result2 = float(len(overlap)) / len(setB) * 100
result3 = float(len(overlap)) / len(universe) * 100