Hash Maps

URL is below

I was taught since python does not have an array, it uses a list instead. But in this exercise a list seems to have keys. "I thought only dictionaries have keys?

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

  def assign(self, key, value):
    array_index = self.compressor(self.hash(key))
    current_array_value = self.array[array_index]

    if current_array_value is None:
      self.array[array_index] = [key, value]

    if current_array_value[0] == key:
      self.array[array_index] = [key, value]

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

The only time you’re making use of any kind of indexing is with self.array[array_index] (or current_array_value[0]). So what kind of value does array_index have? Is it like a dictionary key and accepts almost any immutable object or is it restricted to integers associated with the indices of a list?

Why not print it and see. Consider what the hash method is designed to do.

1 Like