Interesting Collections

Ramon Echeverria
2 min readFeb 22, 2021

During my first mock technical interview, I was given a very simple algorithm question. While I dont remember the exact wording, I was given a string and was asked to return an object with key value pairs, that were to be each letter and a count of how often it shows up in the string.

So essentially, take const string = ‘aassfbkhbfkjb’ return {a:2, s:2 … } etc. My original method was to iterate through the string and create the key value pairs, and updating the count as I worked through my string. At the end, return the object. As an example, in Javascript I wrote

As I’ve mentioned previously, I’ve been working in Python with a study group and a similar problem came up and someone used Counter. This was new to me, since it was an import and I’m not terrible familiar with the standard libraries in Python. Enter ‘ from collections import Counter’

Now Collections is a module gives you access to various containers, which are objects that store other objects. You can also iterate through them. Python is powerful, and when I tried counter in my example I was able to return the key value pairs in an object, in pretty much 2 lines of code. Check this out :)

I mean, Python did some work behind the scenes but wow. Still 2 lines of code, is something to take notice. The order is different but the key value pairs line up, in a alphabet soup ind of way haha.

As always, it raised the question what other built in functions or libraries, are we not using in any language we are programming in? There’s definitely more built into collections with Python, and I’m excited to make some smaller rabbit holes into some of the more fringe parts of programming.

Till next time :)

--

--