Archive for July 6, 2010

Bags or multisets in python

On first inspection that python Counter object didn’t look like a multiset (or bag) to me… I’m not quite sure why.
Regardless a bag it is.

It doesn’t have a ‘subset’ operator but the subtraction operator is a reasonable substitute. (Or you could subclass it and define your own)

Example of using a Counter as a bag:
def is_subset(a, b):
return not bool(a – b)
import collections
print is_subset(collections.Counter(‘ook’), collections.Counter(‘book’))
print is_subset(collections.Counter(‘ook’), collections.Counter(‘ok’))

Advertisements

July 6, 2010 at 11:37 pm Leave a comment


July 2010
M T W T F S S
« Jun   Aug »
 1234
567891011
12131415161718
19202122232425
262728293031