Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python multiply two collection counters

Python collection counter Curious if there is a better way to do this. Overriding a Counter class method? The built-in multiply produces the dot product of two counters

from collections import Counter
a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})    
newcounter = Counter()
for x in a.elements():
    for y in b.elements():
        if x == y:
             newcounter[x] = a[x]*b[y]

$ newcounter
Counter({'b': 32, 'c': 8, 'a': 2})
like image 569
codervince Avatar asked Mar 01 '16 10:03

codervince


3 Answers

Assuming a and b always have the same keys, you can achieve this with a dictionary comprehension as follows:

a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})
c = Counter({k:a[k]*b[k] for k in a})
print(c)

Output

Counter({'b': 32, 'c': 8, 'a': 2})
like image 166
gtlambert Avatar answered Sep 20 '22 01:09

gtlambert


You can get the intersection of the keys if you don't have identical dicts:

from collections import Counter

a = Counter({'b': 4, 'c': 2, 'a': 1, "d":4})
b = Counter({'b': 8, 'c': 4, 'a': 2})

# just .keys() for python3
print Counter(({k: a[k] * b[k] for k in a.viewkeys() & b}))
Counter({'b': 32, 'c': 8, 'a': 2})

Or if you want to join both you can or the dicts and use dict.get:

from collections import Counter

a = Counter({'b': 4, 'c': 2, 'a': 1, "d":4})
b = Counter({'b': 8, 'c': 4, 'a': 2})


print Counter({k: a.get(k,1) * b.get(k, 1) for k in a.viewkeys() | b})
Counter({'b': 32, 'c': 8, 'd': 4, 'a': 2})

If you wanted to be able to use the * operator on the Counter dicts you would have to roll your own:

class _Counter(Counter):
    def __mul__(self, other):
        return _Counter({k: self[k] * other[k] for k in self.viewkeys() & other})

a = _Counter({'b': 4, 'c': 2, 'a': 1, "d": 4})
b = _Counter({'b': 8, 'c': 4, 'a': 2})

print(a * b)

Which would give you:

_Counter({'b': 32, 'c': 8, 'a': 2})

If you wanted inplace:

from collections import Counter


class _Counter(Counter):
    def __imul__(self, other):
        return _Counter({k: self[k] * other[k] for k in self.viewkeys() & other})

Output:

In [28]: a = _Counter({'b': 4, 'c': 2, 'a': 1, "d": 4})

In [29]: b = _Counter({'b': 8, 'c': 4, 'a': 2})

In [30]: a *= b

In [31]: a
Out[31]: _Counter({'a': 2, 'b': 32, 'c': 8})
like image 32
Padraic Cunningham Avatar answered Sep 20 '22 01:09

Padraic Cunningham


This seems a bit better:

a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})    

newcounter = Counter({k:a[k]*v for k,v in b.items()})

>>> newcounter
Counter({'b': 32, 'c': 8, 'a': 2})
like image 26
mhawke Avatar answered Sep 18 '22 01:09

mhawke