Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python: collections.Counter() #26

Open
sophryu99 opened this issue Sep 26, 2021 · 1 comment
Open

Python: collections.Counter() #26

sophryu99 opened this issue Sep 26, 2021 · 1 comment

Comments

@sophryu99
Copy link
Owner

sophryu99 commented Sep 26, 2021

Initialization of Counter class

import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
>>> Counter({'b': 3, 'a': 2, 'c': 1})
>>> Counter({'b': 3, 'a': 2, 'c': 1})
>>> Counter({'b': 3, 'a': 2, 'c': 1})

Time Complexity: O(n)

@sophryu99
Copy link
Owner Author

Create and Update Counters

c = collections.Counter()
print 'Initial :', c

c.update('abcdaab')
print 'Sequence:', c

c.update({'a':1, 'd':5})
print 'Dict    :', c

Find the most common words

import re

words = re.findall('w+', open('hamlet.txt').read().lower())

print Counter(words).most_common(10)

[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant