Some different expectetions in the behaviour of the HashMap

This commit is contained in:
julien lengrand-lambert
2013-11-26 19:07:03 +01:00
parent d63e082551
commit 0267a97f33
2 changed files with 19 additions and 10 deletions

View File

@@ -124,6 +124,7 @@ class HashMapWithItem():
class HMTableCollision(HashMap): class HMTableCollision(HashMap):
""" """
This implementation USES HMItems
Extension of the previous HashMap implementation that takes care of Extension of the previous HashMap implementation that takes care of
collisions. collisions.
Instead of having only one slot available per index in the table, Instead of having only one slot available per index in the table,
@@ -140,12 +141,15 @@ class HMTableCollision(HashMap):
Adds the provided value to the hashmap. Adds the provided value to the hashmap.
Raises an Exception if a collision is detected Raises an Exception if a collision is detected
""" """
# item to be saved in the HM
item = _HashMapItem(key, value)
my_key = self._hash(key) my_key = self._hash(key)
if self.hmap[my_key] == None: if self.hmap[my_key] == None:
self.hmap[my_key] = [value] self.hmap[my_key] = [item]
else: else:
self.hmap[my_key].append(value) self.hmap[my_key].append(item)
self._size += 1 self._size += 1
def get(self, key): def get(self, key):
@@ -154,14 +158,15 @@ class HMTableCollision(HashMap):
the string we are looking for the string we are looking for
""" """
my_key = self._hash(key) my_key = self._hash(key)
vals = self.hmap[my_key] items = self.hmap[my_key]
if vals is None: if items is None:
return vals return items # Nothing found
elif len(vals) == 1: elif len(items) == 1:
return vals[0] return items[0].v # Returns correct value
else: else:
return vals # we return all the results if there are several # TODO: Change this. Only return the correct result
return items # we return all the results if there are several
def size(self): def size(self):
return self._size return self._size

View File

@@ -53,7 +53,7 @@ class test_hash_map_table_collision(unittest.TestCase):
hm.add("a", "Ibiza2") hm.add("a", "Ibiza2")
self.assertEqual(hm.size(), 2) self.assertEqual(hm.size(), 2)
# TODO: Should return exception. Not allow twice the same key!
def test_get(self): def test_get(self):
hm = HMTableCollision() hm = HMTableCollision()
@@ -78,7 +78,11 @@ class test_hash_map_table_collision(unittest.TestCase):
self.assertEqual(hm.get(key2), value2) self.assertEqual(hm.get(key2), value2)
self.assertEqual(hm.get("Five"), None) self.assertEqual(hm.get("Five"), None)
self.assertEqual(hm.get(key), [value, value3])
# Two tests to be done :
# Exact same key already exists : We return an error
# Different keys, but collision anyway, we return the correct value
#self.assertEqual(hm.get(key), )
class test_hash_map_with_item(unittest.TestCase): class test_hash_map_with_item(unittest.TestCase):