EXOR or symmetric difference for the Counter class

Raymond Hettinger python at rcn.com
Sat Aug 14 19:14:14 CEST 2010


On Aug 12, 1:20 pm, Paddy <paddy3... at googlemail.com> wrote:
> I find myself needing to calculate the difference between two Counters
> or multisets or bags.
>
> I want those items that are unique to each bag.

Tell us about your use cases.  I'm curious how a program would ascribe
semantic meaning to the result.  The phrase "unique to each bag"
doesn't quite cover it, perhaps something like "number in either
source above the minimum held in common".

AFAICT, I've never needed something like this as a primitive.  Even
the xor operation for regular sets is rarely used.


> I know how to
> calculate it:
>
>     >>> b = Counter(a=1, b=2)
>     >>> c = Counter(a=3, b=1)
>     >>> diff = (b - c) + (c - b)
>     >>> diff
>     Counter({'a': 2, 'b': 1})

That seems simple enough.
You could also use:

 diff = (b | c) - (b & c)   # max(b,c) - min(b,c)


Raymond



More information about the Python-list mailing list