Counting Without Counter
In the previous lesson, I gave an overview of the course. In this lesson, I’ll introduce you to solving counting problems without Python’s
Counter class, doing it the hard way first. My mother would be proud.
00:22 How many things are there in that sequence? Finding the length of a sequence is only at the beginning, though. What about grouping things together in your data? Counting these kinds of things is called determining the frequency of an occurrence.
00:49 What if you wanted to count the occurrences of each of the letters in the word? You could create a dictionary, then for each letter in the word, check if that letter is already in your dictionary.
and then either way, increment the counting value. Looking at the result in the dictionary, you’ll see a key for each unique letter and the corresponding count of the letter as the value: one
's's, and two
01:32 By the time you’re done, you’re going to be tired of Mississippi, I promise. Initializing a new key in the dictionary can be done in other ways. Let’s skin the proverbial cat—what a horrid expression!
and this time, instead of a conditional to initialize the value and a line increment, it can be done in a single statement. The
.get() method of a dictionary takes a default value parameter. So in this case, either the letter is fetched and then incremented or
0 is returned and incremented.
And this time, instead of creating an empty
dict, you create a new
defaultdict class, passing in
int. The hint here is in the class’s name. It is a dictionary with a default value. Passing in
int means that if a key isn’t found, create it, setting it to an integer.
Looking at the counter, you see that it looks a little different, as the result isn’t a plain old dictionary, but a default one. The counts inside are the same, and as
defaultdict inherits from
dict, anything you can do with the base class you can do with this fancier one. Okay.
Become a Member to join the conversation.