I have two strings and I would like to have the intersection on them including duplicate items:
str_a = \"aabbcc\"
str_b = \"aabd\"
list(set(str_a)
Use collections.Counter for each word and use these 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'
The Counter is a dict subclass, but one that counts all the elements of a sequence you initialize it with. Thus, "aabbcc" becomes Counter({'a': 2, 'b': 2, 'c': 2}).
Counters act like multisets, in that when you use 2 in an intersection like above, their counts are set to the mimimum values found in either counter, ignoring anything whose count drops to 0. If you were to compute their union, the maximum counts would be used instead.