mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Starts implementing add method of version with collisions.
This commit is contained in:
@@ -55,4 +55,24 @@ class HashMap():
|
||||
|
||||
return h % self._hash_size
|
||||
|
||||
|
||||
class HMTableCollision(HashMap):
|
||||
"""
|
||||
Extension of the previous HashMap implementation that takes care of
|
||||
collisions.
|
||||
Instead of having only one slot available per index in the table,
|
||||
each index will contain a list. This means several elements can be
|
||||
stored with the same index.
|
||||
"""
|
||||
def add(self, key, value):
|
||||
"""
|
||||
Adds the provided value to the hashmap.
|
||||
Raises an Exception if a collision is detected
|
||||
"""
|
||||
my_key = self._hash(key)
|
||||
|
||||
|
||||
if self.hmap[my_key] == None:
|
||||
self.hmap[my_key] = value
|
||||
self._size += 1
|
||||
else:
|
||||
raise Exception("Collision detected at index %d", key)
|
||||
|
||||
@@ -5,9 +5,21 @@ Unit tests for the Hash Map table implementation
|
||||
"""
|
||||
|
||||
from hm import HashMap
|
||||
from hm import HMTableCollision
|
||||
|
||||
import unittest
|
||||
|
||||
class test_hash_map_table_collision(unittest.TestCase):
|
||||
|
||||
def test_add(self):
|
||||
hm = HMTableCollision()
|
||||
|
||||
hm.add("a", "Ibiza")
|
||||
self.assertEqual(hm.size(), 1)
|
||||
|
||||
# Tests Collision
|
||||
self.assertRaises(Exception, lambda x : hm.add("a", "Ibiza"))
|
||||
self.assertEqual(hm.size(), 1)
|
||||
|
||||
class test_hash_map(unittest.TestCase):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user