Use collections.Counter for each word and use them as sets:
>>> from collections import Counter >>> str_a, str_b = 'aabbcc', 'aabd' >>> Counter(str_a) & Counter(str_b) Counter({'a': 2, 'b': 1}) >>> ''.join((Counter(str_a) & Counter(str_b)).elements()) 'aab'
Counter is a subclass of dict , but one that counts all the elements of the sequence with which you initialize it. Thus, "aabbcc" becomes Counter({'a': 2, 'b': 2, 'c': 2}) .
Counters act as multisets, in the case when you use 2 at the intersection, as described above, their counts are set to the minimum values ββfound in any of them, ignoring all, the number of which drops to 0. If you had to calculate their union, maximum values ββwill be used instead.
Martijn pieters
source share