Subtraction of Counter objects with negative values included in result

Viewed 547

I was trying to subtract two counter objects in a way that zero and negative values are included in the resultant counter but wasn't getting the desired output. The sample block of code '`

1- dic = {'1':6 , '2':4 , '3':2}
2- dic2 = {'1':3 , '2':1 , '3':5}
3- obj1 = Counter(dic)
4- obj2 = Counter(dic2)
5- obj = obj1-obj2 
6- print(obj) 
#Output
Counter({'1':3 , '2':3}) #it omits the '3':-3 part

#In line 5 I also used subtract() but it is returning none 
5 - obj = obj1.subtract(obj2)
#output
None
2 Answers

You can use subtract method of Counter for this.

In [23]: c = Counter(a=4, b=2, c=0, d=-2)
    ...: d = Counter(a=1, b=2, c=3, d=4)
    ...: c.subtract(d)
    ...: c
Out[23]: Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

Note: Counter('abbbc') - Counter('bccd') also Subtract count, but keep only results with positive counts.

Subtraction of Counter by obj1 - obj2 only keep positive counts and return the Counter, while obj1.subtract(obj2) keep negative counts but it changes obj1 in-place and return None.

Therefore, you are assigning obj to None, you can find that obj1 is actually subtracted.

obj1 = Counter({'1':6, '2':4, '3':2})
obj2 = Counter({'1':3, '2':1, '3':5})
obj = obj1.subtract(obj2)
print(obj)
print(obj1)

Output:

None
Counter({'1': 3, '2': 3, '3': -3})

You can just remove the assignment and print(obj1), or make a copy first if you want to keep obj1.

# 1. change obj1
obj1.subtract(obj2)
print(obj1)
# 2. keep obj1
obj = obj1.copy()
obj.subtract(obj2)
print(obj)
Related