How to test if a python Counter
is contained in another one using the following definition:
A Counter
a
is contained in a Counterb
if, and only if, for every keyk
ina
, the valuea[k]
is less or equal to the valueb[k]
. TheCounter({'a': 1, 'b': 1})
is contained inCounter({'a': 2, 'b': 2})
but it is not contained inCounter({'a': 2, 'c': 2})
.
I think it is a poor design choice but in python 2.x the comparison operators (<
, <=
, >=
, >
) do not use the previous definition, so the third Counter is considered greater-than the first. In python 3.x, instead, Counter
is an unorderable type.
The best I came up with is to convert the definition i gave in code:
But if feels strange that python don't have an out-of-the-box solution and I have to write a function for every operator (or make a generic one and pass the comparison function).
For all the keys in smaller
Counter
make sure that no value is greater than its counterpart in the biggerCounter
:While
Counter
instances are not comparable with the<
and>
operators, you can find their difference with the-
operator. The difference never returns negative counts, so ifA - B
is empty, you know thatB
contains all the items inA
.