[Python Tips] Counter

in #programming6 years ago

Counter

Counter is a collections object that keeps count of how many times similar values are found. Counter is part of the collections module and is a default package, so you do not need to install it.

The most commonly used function is ironically most_common(), which returns the most frequently found values.

Let's go through an example and it should make a lot of sense.

Example

import collections
c = collections.Counter()
c.update('I know it is wet and the sun is not sunny, but we can have lots of good fun that is funny')
c.most_common(3)

The output should look like this:
[(' ', 21), ('n', 10), ('t', 8)]

The most common occurrence is the space coming in at 21 times, followed by n for 10 times and t 8 times.

If you just print(c) the counter object you will see this:

Counter({' ': 21, 'n': 10, 't': 8, 'o': 6, 's': 6, 'u': 5, 'i': 4, 'e': 4, 'a': 4, 'w': 3, 'h': 3, 'f': 3, 'd': 2, 'y': 2, 'I': 1, 'k': 1, ',': 1, 'b': 1, 'c': 1, 'v': 1, 'l': 1, 'g': 1})

You can also interact with a counter using dictionary calls, like the following:

c['n']

returns 10.

Counters also expose an elements() function that allows you to iterate throughout the values.

for value in c.elements():
   print(value)

Counter Math

Counters can be combined with other counters, using +, -, &, and |.

+ and - work as expected, it combines or subtracts the elements of two counters.
& returns the insection of two counters, the minimum value from both counters.
| returns the union of the two counters, the maximum value from both counters.

c3 = c1 + c2
c3 = c1 - c2
c3 = c1 & c2
c3 = c1 | c2

My Python Tips Series

Sort:  

Wow, this is nice. So counter keeps count of how times a similar value was found?. I never really knew. Thanks for making us understand the meaning of counter. This is my first time hearing it. Thanks for sharing another wonderful post

- UFF! me funciono mucho. Realmente interesante aprender nuevos "TIPS" de personas experimentadas en el lenguaje de programación "PYTHON" se te agradece mucho el aporte ya que estas instruyendo a muchos a seguir adelante en este hermosos mundo de la tecnología.

Que buen post , me encanto interesante ,saludos.

not a big fan of mathematics but I think am interested. One question though how do we apply this in real life situations.

How long would it take me to learn python

You can learn Python in a couple of days, but getting good at it takes time. It's more learning the things you will interact with than learning the language.

That's really cool
Where can I learn