Tests add with collisions

This commit is contained in:
Julien Lengrand-Lambert
2013-11-24 16:20:14 +01:00
parent f66c95d8da
commit 2144671096
2 changed files with 49 additions and 19 deletions

View File

@@ -25,8 +25,6 @@ class HashMap():
else:
raise Exception("Collision detected at index %d", key)
# TODO: Keep implementing
def get(self, key):
"""
Finds the element in the hash table that may contain the id for
@@ -63,6 +61,11 @@ class HMTableCollision(HashMap):
each index will contain a list. This means several elements can be
stored with the same index.
"""
def __init__(self, hash_size=513):
self._hash_size = hash_size
self._size = 0
self.hmap = [None] * self._hash_size
def add(self, key, value):
"""
Adds the provided value to the hashmap.
@@ -70,9 +73,36 @@ class HMTableCollision(HashMap):
"""
my_key = self._hash(key)
if self.hmap[my_key] == None:
self.hmap[my_key] = value
self._size += 1
self.hmap[my_key] = [value]
else:
raise Exception("Collision detected at index %d", key)
self.hmap[my_key].append(value)
self._size += 1
def get(self, key):
"""
Finds the element in the hash table that may contain the id for
the string we are looking for
"""
my_key = self._hash(key)
return self.hmap[my_key]
def size(self):
return self._size
def _hash(self, value):
"""
Generates a hash for the given value.
The input is expected to be a String, with only ASCII characters.
# hash function taken from HT3.
# We shift and add : << 4 is a *16
"""
if len(value) < 1:
raise Exception("Size of value must be greater than one")
h = 0
for letter in value:
h = (h << 4) + ord(letter)
return h % self._hash_size

View File

@@ -17,9 +17,8 @@ class test_hash_map_table_collision(unittest.TestCase):
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)
hm.add("a", "Ibiza")
self.assertEqual(hm.size(), 2)
class test_hash_map(unittest.TestCase):
@@ -47,6 +46,7 @@ class test_hash_map(unittest.TestCase):
value = ""
self.assertRaises(Exception, lambda x : hm._hash(value))
def test_add(self):
hm = HashMap()