Implements a first get method. This doesnt take collisions into account yet. Also, we use strings to retrieve strings . . . Not really clever

This commit is contained in:
Julien Lengrand-Lambert
2013-11-21 19:57:32 +01:00
parent 7f8736c9ca
commit af8014a79a
2 changed files with 14 additions and 5 deletions

View File

@@ -27,12 +27,10 @@ class HashMap():
def get(self, value): def get(self, value):
""" """
Finds the element in the hash table that may contain the id for Finds the element in the hash table that may contain the id for
the string ze are looking for the string we are looking for
""" """
key = self._hash(value) key = self._hash(value)
return self.hmap[key] return self.hmap[key]
def size(self): def size(self):
return self._size return self._size
@@ -41,12 +39,13 @@ class HashMap():
""" """
Generates a hash for the given value. Generates a hash for the given value.
The input is expected to be a String, with only ASCII characters. 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: if len(value) < 1:
raise Exception("Size of value must be greater than one") raise Exception("Size of value must be greater than one")
# hash function taken from HT3.
# We shift and add : << 4 is a *16
h = 0 h = 0
for letter in value: for letter in value:
h = (h << 4) + ord(letter) h = (h << 4) + ord(letter)

View File

@@ -51,6 +51,16 @@ class test_hash_map(unittest.TestCase):
value = "" value = ""
self.assertRaises(Exception, lambda x : hm.get(value)) self.assertRaises(Exception, lambda x : hm.get(value))
value = "One"
hm.add(value)
hm.add("Two")
hm.add("Three")
hm.add("Four")
self.assertEqual(hm.size(), 4)
self.assertEqual(hm.get(value), value)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()