#100DaysOfCode in Python Transcripts
Chapter: Days 4-6: Collections module
Lecture: Counter: don't reinvent the wheel
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's move on with Counter.
0:02
Let's say we have a text which is split into words,
0:06
and we want to count the most common words.
0:11
Before I knew about collections,
0:14
I would write something like this.
0:26
There you go.
0:28
I had to loop over words, keep a dictionary,
0:32
see if the key was in the dictionary,
0:35
if not, initialize to zero.
0:38
If it's in there do plus one.
0:39
Then I had to loop over the items over the key value pairs,
0:45
sort them and use lambda to sort by value.
0:49
In reversed order and take a slice to get it to five.
0:53
Now compare that with using Counter,
0:55
and its most common method.
1:00
It's like magic, right?
1:02
One line of code, you pass the words list into the Counter,
1:06
and you call most common and you give the number
1:09
of top words you want to see and compare that
1:13
with all the work I had to do here and how easy it gets
1:17
by using the collections, Counter.