mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Finishes implementing hash method
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
Reference in New Issue
Block a user