Mainly Tech projects on Python and Electronic Design Automation.

Sunday, December 03, 2017

Contradictory Counter() calculations.

The issue

I just got caught by this issue with doing maths with collections.Counter classes.
In [5]:
from collections import Counter

a = Counter(x=1, y=2)
b = Counter(x=1, y=2, z = 0)
In [6]:
a == b
Out[6]:
False
Now, it is quite obvious that the above is False as they are given as two different values, but In the case of Counters the count of b['z'] is zero and when counting in two different ways, or doing addition or subtraction of counts then you can end up with zero counts on items and because their is a difference in zero counted items then two Counter instances with otherwise the same counts are not considered ==.
I found that the best way around this is to subtract and compare to the empty Counter, as it seems subtraction removes zero counted items.
In [7]:
a - b == Counter()
Out[7]:
True
The docs say the unary plus operator removes zero and negative counted items whichmay be what you want, but is subtly different:
In [8]:
+a == +b
Out[8]:
True
But
In [12]:
c = Counter(x=1, y=2, z = -1)
In [11]:
+a == +b == +c
Out[11]:
True
In [13]:
a - c
Out[13]:
Counter({'z': 1})
In [14]:
a - b
Out[14]:
Counter()

Summary

I guess you need to be aware of this when using the excellant collections.Counter.

END.

No comments:

Post a Comment

Followers

Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

whos.amung.us

Blog Archive