Starts implementing add method of version with collisions.

This commit is contained in:
Julien Lengrand-Lambert
2013-11-23 18:06:43 +01:00
parent 1ec8b0672c
commit f66c95d8da
2 changed files with 33 additions and 1 deletions

View File

@@ -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)

View File

@@ -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):