I have just completed a fun exercise on HackerRank named Company Logo. The task was to “print the three most common characters along with their occurrence count”.
Task
Two key conditions were:
- Sort in descending order of occurrence count,
- If the occurrence count is the same, sort the characters in alphabetical order.
As with most of the problems, there is more than one solution, but because I recently explored the collections module and DefaultDict in particular, it was the first thing that came to my mind - I would insert each character into the dictionary and on each occurence increment the value by 1.
The more challenging condition came afterwards, where I had to sort it first by value and if the value is the same, by the key. Here I used the built-in sorted() function and it was an opportunity to understand this function more deeply because it can be used in a variety of ways.
Example:
Sample input:
|
|
Sample output:
|
|
My Solution
|
|
Output from the example:
|
|
Everytime I finish an exercise I check the discussion for the solutions of other users - to learn and see other ways of achieving the same goal. Indeed there were many solutions, some of which looked like magic (having only 2-3 lines), but these kinds of solutions sometimes compromise readability of the code, which is also a very important part of a clean code.