From 214467109682a6729c4a164bcf56ed3741891d78 Mon Sep 17 00:00:00 2001 From: Julien Lengrand-Lambert Date: Sun, 24 Nov 2013 16:20:14 +0100 Subject: [PATCH] Tests add with collisions --- 02_hash_maps/hm.py | 58 +++++++++++++++++++++++++++++++---------- 02_hash_maps/hm_test.py | 10 +++---- 2 files changed, 49 insertions(+), 19 deletions(-) diff --git a/02_hash_maps/hm.py b/02_hash_maps/hm.py index 7c405a5..37c8aa1 100644 --- a/02_hash_maps/hm.py +++ b/02_hash_maps/hm.py @@ -24,9 +24,7 @@ class HashMap(): self._size += 1 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,16 +61,48 @@ 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. - Raises an Exception if a collision is detected - """ - my_key = self._hash(key) + """ + 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] + else: + 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) - - if self.hmap[my_key] == None: - self.hmap[my_key] = value - self._size += 1 - else: - raise Exception("Collision detected at index %d", key) + return h % self._hash_size diff --git a/02_hash_maps/hm_test.py b/02_hash_maps/hm_test.py index 21f1e8a..0b92b08 100644 --- a/02_hash_maps/hm_test.py +++ b/02_hash_maps/hm_test.py @@ -10,16 +10,15 @@ 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) + + 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()