Comparing two different python counter objects
Those operations are already built-in to the Counter type:
Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts.
(Quoted from Python collections.Counter
docs.)
So assuming D1
and D2
are Counters, try
R1 = D1 & D2
R2 = D2 - R1
If by shared letters you mean the Counter intersection, you can use the &
operator and the amount of letters needed to convert R1
into R2
can be seen as the difference:
from collections import Counter
D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5})
D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7})
R1 = D1 & D2
print(R1) # intersection: min(c[x], d[x])
print(D2 - D1) # subtract (keeping only positive counts)
Output
Counter({'D': 5, 'C': 4, 'A': 2, 'B': 1})
Counter({'B': 3, 'D': 2, 'A': 1})
If you want to keep negative counts, you can do it like this:
from collections import Counter
D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5, 'E': 5})
D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7, 'E': 3})
R2 = Counter({key: D2.get(key, 0) - value for key, value in D1.items()})
print(R2)
Output
Counter({'B': 3, 'D': 2, 'A': 1, 'C': 0, 'E': -2})
In the above example 'E' : -2
because the count of E
is 5
in D1
and 3
in D2
. Note: All the examples are in Python 3.5.