If there were no duplicates, or duplicates didn't matter (that is, if your l1
and l3
were both supersets of each other), you'd just use sets. But since if you want l1
to be a proper superset of l3
, you're talking about multisets. Fortunately, Counter
already implements multisets for you:
from collections import Counter
def is_superset(a, b):
return not Counter(b) - Counter(a)
Notice that this -
is proper multiset difference between multisets (just as -
is proper set difference between set
s), not an elementwise subtraction across dicts. So if you subtract a super(multi)set, you get an empty multiset (that is, Counter()
—which is, like all empty collections in Python, falsey).
So now:
>>> is_superset(l1, l2)
True
>>> is_superset(l1, l3)
True
>>> is_superset(l1, l4)
False
>>> is_superset(l1, l5)
False
Plus:
>>> is_superset(l3, l1)
False