Comparing Python counters as type Bag

I need a data type like bag / multiset in Python. I understand the collection. Often used for this purpose. But comparison operators don't seem to work:

In [1]: from collections import Counter

In [2]: bag1 = Counter(a=1, b=2, c=3)

In [3]: bag2 = Counter(a=2, b=2)

In [4]: bag1 > bag2
Out[4]: True

This seems like a mistake to me. I expected operators with fewer and greater numbers than operators to perform subset and supernet mappings. But if this is so, then it bag1 > bag2will be false, because it bag2contains an additional one 'a'. There are also no subset / superset methods on Counter objects. Therefore, I have two questions:

  • What comparison scheme is used for Counter objects?
  • How to compare Counter objects for a subset, subset, the correct subset, and your own superset?
+4
2

Python 2 (Counter dict).

() , (, ) . [5] , , , . [6]

Python 3, TypeError:

() , (, ) . ('<', '< =', ' > =', ' > ') TypeError.

+1

:

Counter , , ?

" ". , .

from collections import Counter

class PartiallyOrderedCounter(Counter):

    def __le__(self, other):
        """ Multiset inclusion """
        return all( v <= other[k] for k,v in self.items() )


    def __lt__(self, other):
        """ Multiset strict inclusion """
        return self <= other and self != other


    # TODO : __ge__ and __gt__
    # Beware : they CANNOT be written in terms of __le__ or __lt__


a = PartiallyOrderedCounter('abc')
b = PartiallyOrderedCounter('ab')
c = PartiallyOrderedCounter('abe')

assert a <= a
assert not a < a    
assert b <= a
assert b < a
assert not a < b    
assert not c <= a
assert not a <= c
0

All Articles