Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Counter in Python that can accumulate negative values? [duplicate]

Tags:

python

counter

I am using a Counter like this:

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

totals += c_one
totals += c_two    

# Output: Counter({'a': 20})
print(totals)

Which is not at all what I expected. I expected to see:

Counter({'a': 20, 'b': -100})

Where did my negatives go, and is there some Counter that will let me use negatives?

like image 382
Wayne Werner Avatar asked May 28 '15 12:05

Wayne Werner


People also ask

How do you handle negative values in Python?

In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.

Does Python recognize negative integers?

There are four basic data types in Python: 1. Numeric: These can be either integers or floats. Integers are positive or negative whole numbers without a decimal point.

What does Counter () do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.


1 Answers

From the docs:

The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.

(emphasis added)

However, if you look a little closer you'll find your answer:

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.

(emphasis added)

All you have to do is make one tiny change, and your example will work:

from collections import Counter

totals = Counter()
c_one = Counter(a=10, b=1)
c_two = Counter(a=10, b=-101)

# Instead of totals += c_one; totals += c_two
totals.update(c_one)
totals.update(c_two)    

# Output: Counter({'a': 20, 'b': -100})
print(totals)
like image 101
Wayne Werner Avatar answered Oct 22 '22 05:10

Wayne Werner