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) & set(str_b))
>> "ab"
I would like to have it return:
>> "aab"
Any ideas?
Multisets are implemented in python 2.7 or later as (mutable) Counter
objects. You can perform many of the same operations as you can for sets, such as union, intersection, difference (though counts can become negative), etc.:
from collections import Counter as mset
Solution:
(mset("aabbcc") & mset("aabd")).elements()
More details:
>>> intersection = mset("aabbcc") & mset("aabd")
Counter({'a': 2, 'b': 1})
>>> list(intersection.elements())
['a', 'a', 'b']
>>> ''.join(intersection.elements())
'aab'
You can use ''.join
if you want a string, or list()
if you want a list, though I would just keep it in iterable format as intersection.elements()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With