mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Modifies HashMap to correspond to the usual scheme
This commit is contained in:
@@ -13,27 +13,27 @@ class HashMap():
|
||||
self._size = 0
|
||||
self.hmap = [None] * self._hash_size
|
||||
|
||||
def add(self, value):
|
||||
def add(self, key, value):
|
||||
"""
|
||||
Adds the provided value to the hashmap.
|
||||
Raises an Exception if a collision is detected
|
||||
"""
|
||||
key = self._hash(value)
|
||||
if self.hmap[key] == None:
|
||||
self.hmap[key] = value
|
||||
my_key = self._hash(key)
|
||||
if self.hmap[my_key] == None:
|
||||
self.hmap[my_key] = value
|
||||
self._size += 1
|
||||
else:
|
||||
raise Exception("Collision detected at index %d", key)
|
||||
|
||||
# TODO: Keep implementing
|
||||
|
||||
def get(self, value):
|
||||
def get(self, key):
|
||||
"""
|
||||
Finds the element in the hash table that may contain the id for
|
||||
the string we are looking for
|
||||
"""
|
||||
key = self._hash(value)
|
||||
return self.hmap[key]
|
||||
my_key = self._hash(key)
|
||||
return self.hmap[my_key]
|
||||
|
||||
def size(self):
|
||||
return self._size
|
||||
|
||||
@@ -38,11 +38,11 @@ class test_hash_map(unittest.TestCase):
|
||||
def test_add(self):
|
||||
hm = HashMap()
|
||||
|
||||
hm.add("a")
|
||||
hm.add("a", "Ibiza")
|
||||
self.assertEqual(hm.size(), 1)
|
||||
|
||||
# Tests Collision
|
||||
self.assertRaises(Exception, lambda x : hm.add(a))
|
||||
self.assertRaises(Exception, lambda x : hm.add("a", "Ibiza"))
|
||||
self.assertEqual(hm.size(), 1)
|
||||
|
||||
def test_get(self):
|
||||
@@ -51,16 +51,17 @@ class test_hash_map(unittest.TestCase):
|
||||
value = ""
|
||||
self.assertRaises(Exception, lambda x : hm.get(value))
|
||||
|
||||
value = "One"
|
||||
hm.add(value)
|
||||
key = "One"
|
||||
value = "Ibiza"
|
||||
hm.add(key, value)
|
||||
|
||||
hm.add("Two")
|
||||
hm.add("Three")
|
||||
hm.add("Four")
|
||||
hm.add("Two", "NY")
|
||||
hm.add("Three", "Berlin")
|
||||
hm.add("Four", "Chicago")
|
||||
|
||||
self.assertEqual(hm.size(), 4)
|
||||
|
||||
self.assertEqual(hm.get(value), value)
|
||||
|
||||
self.assertEqual(hm.get(key), value)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user