I have two string and I will like to compare is the number of character matched each other. The away I think of is to use collections.Counter to build a Counter object with character as key and display frequency as value and then use == to compare if it is matched. But my question leads to if it is valid to use == to compare two Counter objects? does that compare each keys and value all identical?
ex:
string_one = 'aaaaab'
string_two = 'aabaaa'
Counter(string_one) == Counter(string_two) # should be True
string_one = 'aaaaab'
string_two = 'aabaac'
Counter(string_one) == Counter(string_two) # should be False
CodePudding user response:
Yes
per: https://docs.python.org/3/library/collections.html#collections.Counter
Counters support rich comparison operators for equality, subset, and superset relationships: ==, !=, <, <=, >, >=. All of those tests treat missing elements as having zero counts so that Counter(a=1) == Counter(a=1, b=0) returns true.
New in 3.10:
Changed in version 3.10: In equality tests, missing elements are treated as having zero counts. Formerly, Counter(a=3) and Counter(a=3, b=0) were considered distinct.
CodePudding user response:
Yes, two Counters compare equal if and only if they have the same keys, and each key maps to the same value. The docs don't say that straight out, but it's implied by its saying "a Counter is a dict subclass". From that you can deduce that a Counter acts like a dict unless otherwise specified. Then, from the dict docs:
Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError. Blockquote
Although, as @JonSG's answer partly says, some changes were made to this starting in version 3.10. For example,
>>> from collections import Counter
>>> a = Counter()
>>> b = Counter()
>>> a[3] = 0
>>> a
Counter({3: 0})
>>> b[9837] = 0
>>> b
Counter({9837: 0})
>>> a == b # starting in 3.10 missing acts like they map to 0 in `==`
True
>>>
Whether that's an improvement I leave to your judgment ;-)
