Finishes implementing hash method

This commit is contained in:
Julien Lengrand-Lambert
2013-11-21 11:08:35 +01:00
parent 03ca739a08
commit cccda38920
2 changed files with 17 additions and 2 deletions

View File

@@ -12,8 +12,19 @@ class HashMap():
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.
"""
if len(value) < 1:
raise Exception("Size of value must be greater than one")
return 1
# hash function taken from HT3.
# We shift and add : << 4 is a *16
h = 0
for letter in value:
h = (h << 4) + ord(letter)
return h

View File

@@ -17,8 +17,12 @@ class test_hash_map(unittest.TestCase):
def test__hash(self):
hm = HashMap()
value = "a"
self.assertEqual(hm._hash(value), ord(value))
value = "test"
self.assertEqual(hm._hash("test"), 1)
self.assertEqual(hm._hash(value), 502948)
value = ""
self.assertRaises(Exception, lambda x : hm._hash(value))