mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Some different expectetions in the behaviour of the HashMap
This commit is contained in:
@@ -124,6 +124,7 @@ class HashMapWithItem():
|
||||
|
||||
class HMTableCollision(HashMap):
|
||||
"""
|
||||
This implementation USES HMItems
|
||||
Extension of the previous HashMap implementation that takes care of
|
||||
collisions.
|
||||
Instead of having only one slot available per index in the table,
|
||||
@@ -140,12 +141,15 @@ class HMTableCollision(HashMap):
|
||||
Adds the provided value to the hashmap.
|
||||
Raises an Exception if a collision is detected
|
||||
"""
|
||||
# item to be saved in the HM
|
||||
item = _HashMapItem(key, value)
|
||||
|
||||
my_key = self._hash(key)
|
||||
|
||||
if self.hmap[my_key] == None:
|
||||
self.hmap[my_key] = [value]
|
||||
self.hmap[my_key] = [item]
|
||||
else:
|
||||
self.hmap[my_key].append(value)
|
||||
self.hmap[my_key].append(item)
|
||||
self._size += 1
|
||||
|
||||
def get(self, key):
|
||||
@@ -154,14 +158,15 @@ class HMTableCollision(HashMap):
|
||||
the string we are looking for
|
||||
"""
|
||||
my_key = self._hash(key)
|
||||
vals = self.hmap[my_key]
|
||||
items = self.hmap[my_key]
|
||||
|
||||
if vals is None:
|
||||
return vals
|
||||
elif len(vals) == 1:
|
||||
return vals[0]
|
||||
if items is None:
|
||||
return items # Nothing found
|
||||
elif len(items) == 1:
|
||||
return items[0].v # Returns correct value
|
||||
else:
|
||||
return vals # we return all the results if there are several
|
||||
# TODO: Change this. Only return the correct result
|
||||
return items # we return all the results if there are several
|
||||
|
||||
def size(self):
|
||||
return self._size
|
||||
|
||||
@@ -53,7 +53,7 @@ class test_hash_map_table_collision(unittest.TestCase):
|
||||
|
||||
hm.add("a", "Ibiza2")
|
||||
self.assertEqual(hm.size(), 2)
|
||||
|
||||
# TODO: Should return exception. Not allow twice the same key!
|
||||
def test_get(self):
|
||||
|
||||
hm = HMTableCollision()
|
||||
@@ -78,7 +78,11 @@ class test_hash_map_table_collision(unittest.TestCase):
|
||||
|
||||
self.assertEqual(hm.get(key2), value2)
|
||||
self.assertEqual(hm.get("Five"), None)
|
||||
self.assertEqual(hm.get(key), [value, value3])
|
||||
|
||||
# Two tests to be done :
|
||||
# Exact same key already exists : We return an error
|
||||
# Different keys, but collision anyway, we return the correct value
|
||||
#self.assertEqual(hm.get(key), )
|
||||
|
||||
class test_hash_map_with_item(unittest.TestCase):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user