Check if python counter is contained in another counter

How to check if python is Countercontained in another using the following definition:

A counter is acontained in the counter bif and only if, for each key k, the avalue is a[k]less than or equal to the value b[k]. Counter({'a': 1, 'b': 1})contained in Counter({'a': 2, 'b': 2}), but not contained in Counter({'a': 2, 'c': 2}).

I think it is a bad design choice, but in python 2.x comparison operators ( <, <=, >=, >) do not use the previous definition, therefore, is considered the third counter is greater than the first. In python 3.x, it Counteris an unordered type instead .

+4
source share
3 answers

The best I came up with is to convert the definition I gave in the code:

def contains(container, contained):
    return all(container[x] >= contained[x] for x in contained)

But if it is strange that python does not have a ready-made solution, and I have to write a function for each operator (or make a general one and pass the comparison function).

+5
source

Although instances are Counternot comparable with <and operators >, you can find their difference with the operator -. The difference never returns negative values, so if it is A - Bempty, you know that it Bcontains all the elements in A.

def contains(larger, smaller):
    return not smaller - larger
+8
source

Counter , Counter , :

def containment(big, small):
    return not any(v > big[k] for (k, v) in small.iteritems())

>>> containment(Counter({'a': 2, 'b': 2}), Counter({'a': 1, 'b': 1}))
True
>>> containment(Counter({'a': 2, 'c': 2, 'b': 3}), Counter({'a': 2, 'b': 2}))
True
>>> print containment(Counter({'a': 2, 'b': 2}), Counter({'a': 2, 'b': 2, 'c':1}))
False
>>> print containment(Counter({'a': 2, 'c': 2}), Counter({'a': 1, 'b': 1})
False
0

All Articles