The while loop of this exercise feels like an infinite loop

The while loop for the assign method and the retrieve method of this exercise feel like an infinite loop, at least the assign method does.

It does not give a condition for when to break if all the slots are filled up (that’s, there is no None) and the key does not match anyone in the list. It just continues incrementing the collision counter and never stops.

I was able to come up with this idea, the loop starts from 0 and doesn’t pass the size of the list. If it gets there, it breaks. That’s

   while collision_counter <= self.size:
         do this
         collision_counter += 1

Maybe someone has a better idea. That way, it stops once it has circled the whole list.

Here is the code snippet.

  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]

    # Collision!

    number_collisions = 1

    while(current_array_value[0] != key):
      new_hash_code = self.hash(key, number_collisions)
      new_array_index = self.compressor(new_hash_code)
      current_array_value = self.array[new_array_index]

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

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

      number_collisions += 1



Are you talking about how it breaks if it gets assigned over its size limit?


hashc = HashMap(5)
hashc.assign('joni', 'friend')
hashc.assign('onij', 'acquaintance')
hashc.assign('jnio', 'acquaintance')
hashc.assign('onji', 'acquaintance')
hashc.assign('jnoi', 'acquaintance')
hashc.assign('join', 'acquaintance')

#this code won't run because there's one too many assignments with the CC solution code

You can surround the assign function with a while loop that doesn’t accept anything that surpasses its initialized size. It was a good lesson for me to remember not to take someone else’s code at face value without thoroughly testing it.