FAQ: Hash Maps: Python - Creating the Compression Function

This community-built FAQ covers the “Creating the Compression Function” exercise from the lesson “Hash Maps: Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

Complex Data Structures

FAQs on the exercise Creating the Compression Function

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Basic question on the use of variables in the .hash() method. Between exercises 2 and 3, the variable type of key_bytes is inconsistent. In exercise 3, the “correct” code is as follows:

class HashMap:
  def __init__(self, array_size):
    self.array_size = array_size
    self.array = [None for item in range(array_size)]

  def hash(self, key):
    key_bytes = key.encode()
    hash_code = sum(key_bytes)
    return hash_code

  def compressor(self, hash_code):
    return hash_code % self.array_size

Should key_bytes instead be an instance variable self.key_bytes?

Hi @chsgray,

key_bytes is a local variable within the hash method that is not needed outside that method. Therefore, there is no need to establish it as an instance variable. It is actually provided to offer clarity to a programer who reads the code by computing the result in two steps. We could dispense with that variable entirely, as follows:

  def hash(self, key):
    # key_bytes = key.encode()
    hash_code = sum(key.encode())
    return hash_code

We could even do this:

  def hash(self, key):
    return sum(key.encode())
3 Likes

Thanks. This helped me establish more conceptual clarity.

1 Like

Why do we define a separate .compressor() method within the class HashMap? This seems unnecessary. Would it not be easier to compress the hash value via mod within the .hash() function and return the resulting value, rather than add an entirely new method?

Obviously the two work the same, but maybe there is convention here of which I am unaware.