Home > Blockchain >  Python adding Counter objects with negative numbers fails
Python adding Counter objects with negative numbers fails

Time:08-24

why do adding an empty counter to another with a negative value results in 0

from collections import Counter
a=Counter({'a':-1})
b=Counter()
print(a b)

Result

Counter()

but if the counter added to the empty one has a positive value it works

CodePudding user response:

Because when you add counters together, any entry in the result with a total of zero or less is omitted by definition in the docs.

Here are the docs: https://docs.python.org/3/library/collections.html#collections.Counter:~:text=Several mathematical operations,zero or less.

So that this answer is self-contained, the docs read:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

CodePudding user response:

Counter filters out the keys which have counts of zero or less. See the docs:

Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

However, the update method does preserve the mentioned values.

from collections import Counter


a = Counter({'a':-1})
b = Counter()
a.update(b)

print(a) # Counter({'a': -1})
  • Related