equal unequal Counters

>>> import collections
>>> collections.Counter("abc") == collections.Counter("cab")
True
>>> collections.Counter("abc").most_common()
[('a', 1), ('b', 1), ('c', 1)]
>>> collections.Counter("cab").most_common()
[('c', 1), ('a', 1), ('b', 1)]

As demonstrated above, collections.Counter.most_common orders elements with equal counts in order of first appearance: “Elements with equal counts are ordered in the order first encountered”.

But == looks at set equality. Handy for checking for palindromes without doing a sort (and so hopefully O(n) vs O(n log n)): Counter(s) == Counter(t).

Just slightly disconcerting to have two objects that will return True for == but yet still have non-identical results for another method.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *