Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list intersection with non unique items

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?

like image 741
RickyA Avatar asked Sep 03 '12 19:09

RickyA


1 Answers

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().

like image 118
ninjagecko Avatar answered Oct 18 '22 04:10

ninjagecko