Search code examples
python-3.xcounter

Subtraction of Counter objects with negative values included in result


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

Solution

  • 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)