Understanding the Problem

We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses a HashMap, or a dictionary in Python.

For a quick illustration, consider this list of colors:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']

If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ HashMaps for a more efficient counting process.

Introducing HashMaps

Simple yet powerful, HashMaps allow us to store and retrieve data using keys. The unique colors in our list act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors list using a Python dictionary:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_dict = {}

# Start the loop to iterate over each color
for color in colors:
    
    # If the color is present in our dictionary, increment its value by 1
    if color in color_dict:
        color_dict[color] += 1
     
    # If the color isn't present, it means we're encountering this color in our list for the first time. In this case, we add it to our dictionary and set its value to 1
    else:
        color_dict[color] = 1

# At the end of the loop, print our dictionary with counts
print(color_dict)
# prints {'red': 2, 'blue': 3, 'green': 1}

When the above code executes, it displays the counts for each color: {'red': 2, 'blue': 3, 'green': 1}.

Understanding the above solution

Here's how we created a dictionary to count our elements:

We began with an empty dictionary. Then, we went through our list, and for every occurring element, we checked if it was in our dictionary. If it was, we increased its value. If it was not, we added it to the dictionary with a value of 1.

Consequently, this code efficiently counts the colors in our list, showcasing how performant counting can be, even as the list size increases!

Python dictionaries have a get(key, default) method, which is an alternative to checking whether a key already exists in a dictionary. It allows us to fetch the value of a key if it exists, or return a default value specified by you if it doesn't.

The code above can be also written like this:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_dict = {}

# Start the loop to iterate over each color
for color in colors:
    
    # Get the value of the color key if it exists, otherwise use a default value of 0. Then increment the value by 1
    color_dict[color] = color_dict.get(color, 0) + 1

# At the end of the loop, print our dictionary with counts
print(color_dict)
# prints {'red': 2, 'blue': 3, 'green': 1}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal