Using Counters in Python

Python never ceases to amaze me! I came across yet another amazing trick in Python which is not very well known but can be extremely useful for programmers.
I dunno how many of you are familiar with using Counter class, but I found it really interesting.

A Counter is basically a { Key : Value} pair type of a map and when a string is passed onto it, it denotes frequencies of all the letters occuring in a string. I wrote a simple python script to implement the Counter class, which I encourage you try running on your machine as well.

Counters1.py  Counters1_Output

First we have to import the module Counter from collections and then we pass any string to it.
Counter(Some_string) returns to us the frequency of each occuring letter in the string, as you can see in the output. This is extremely useful for a number of applications, one of the most spontaneous use of this trick could be in coding text compression and cryptographic algorithms like Huffman, Run Length Encoding where we have to otherwise run for loops and use arrays to find out this frequency of each letter.
This simple magic of Python saves us a lot of hassles.

One other application I would like to mention is that of checking if two strings are anagrams (a word with same number of letters, but in a re-arranged manner).
Check out the following code:-

Counters2.py   Counters2_OP

The first string, string1 is my name ‘Divyansh’ and in the second string, string2 I rearranged the letters in my name. When I check for the equality of the two strings, I get a false (obviously!), but when I compare their Counter, I’m basically comparing the frequency of each letter in the two strings, which is what the check for an anagam is. Hence, my script prints True in case of an anagram.

Do play with Counter by using your own name, or any other string. I’ll edit this post when I find more uses of the Counter class.

– jigsaw