Search code examples
pythonalgorithmcounterinclusion

Test if python Counter is contained in another Counter


How to test if a python Counter is contained in another one using the following definition:

A Counter a is contained in a Counter b if, and only if, for every key k in a, the value a[k] is less or equal to the value b[k]. The Counter({'a': 1, 'b': 1}) is contained in Counter({'a': 2, 'b': 2}) but it is not contained in Counter({'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.


Solution

  • Update 2023: Counter supports rich comparison operators as of python 3.10, so this works:

    container <= contained
    

    Historical answer for python < 3.10:

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

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

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