Anshul Gupta
Anshul Gupta

Reputation: 71

Unexpected python counter value

The output value of code is cnt['yellow'] = zero but the expected value after applying the formula given in the code should be (0 +1)/(6 + (1*3))

from collections import Counter
cnt = Counter()
sm = 1
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1

s = sum(cnt.values())
print(s)

c = len(cnt)
print(c)

for k,v in cnt.items():
    cnt[k] = (cnt[k] + sm)/(s + (sm *c))

print(cnt['yellow'])

Upvotes: 0

Views: 107

Answers (2)

Hesham Attia
Hesham Attia

Reputation: 977

You could add a custom method like:

def getCount(counter, key):
  sm = 1
  s = sum(cnt.values())
  c = len(cnt)
  return (counter[key] + sm)/(s + (sm * c))

And then use it by calling:

print getCount(cnt, "yellow")

Upvotes: 0

Yasin Yousif
Yasin Yousif

Reputation: 967

To apply a function , to any entered value, you could use a class and method , that would be elegant way , I don't know your program , but you may rename the class for better readability , according to what it actually represent like this (this is tested in py2 but should work in py3):

from collections import Counter
lst1 = ['red', 'blue', 'red', 'green', 'blue', 'blue']

class count_helper:
    def __init__(self):
        self.sm = 1.0
        self.cnt = Counter()

    def count_colors(self,lst):
        for w in lst:
            self.cnt[w]+=1.0

    def __call__(self,color='blank'):
        s = sum(self.cnt.values())
        c = len(self.cnt)
        return (self.cnt[color] + self.sm)/(s + (self.sm *c))

cntc = count_helper()
cntc.count_colors(lst1)
print(cntc('yellow'))

Result:

0.111111111111

And :

In [13]: print(cntc('red'))
0.333333333333

In [14]: print(cntc('blue'))
0.444444444444

Upvotes: 1

Related Questions