From f66c95d8da7fcad29f0faf4a1aa910b9fddcf1a3 Mon Sep 17 00:00:00 2001 From: Julien Lengrand-Lambert Date: Sat, 23 Nov 2013 18:06:43 +0100 Subject: [PATCH] Starts implementing add method of version with collisions. --- 02_hash_maps/hm.py | 22 +++++++++++++++++++++- 02_hash_maps/hm_test.py | 12 ++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/02_hash_maps/hm.py b/02_hash_maps/hm.py index a236ce6..7c405a5 100644 --- a/02_hash_maps/hm.py +++ b/02_hash_maps/hm.py @@ -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) diff --git a/02_hash_maps/hm_test.py b/02_hash_maps/hm_test.py index 26b151b..21f1e8a 100644 --- a/02_hash_maps/hm_test.py +++ b/02_hash_maps/hm_test.py @@ -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):