Skip to content

Commit

Permalink
HashTable:
Browse files Browse the repository at this point in the history
1. Fixed documentation
2. added __delitem__
  • Loading branch information
orenovadia committed May 5, 2017
1 parent ee36943 commit 36a7561
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions map/hashtable.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
"""
MAP Abstract Data Type
Map() Create a new, empty map. It returns an empty map collection.
put(key,val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value.
get(key) Given a key, return the value stored in the map or None otherwise.
del Delete the key-value pair from the map using a statement of the form del map[key].
len() Return the number of key-value pairs stored in the map.
in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
"""
from unittest import TestCase


class HashTable(object):
"""
HashMap Data Type
HashMap() Create a new, empty map. It returns an empty map collection.
put(key, val) Add a new key-value pair to the map. If the key is already in the map then replace
the old value with the new value.
get(key) Given a key, return the value stored in the map or None otherwise.
del_(key) or del map[key] Delete the key-value pair from the map using a statement of the form del map[key].
len() Return the number of key-value pairs stored in the map.
in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
"""

_empty = object()
_deleted = object()

def __init__(self, size=11):
self.size = size
self._len = 0
self._keys = [self._empty] * size # keys
self._values = [self._empty] * size # values

Expand All @@ -27,6 +30,7 @@ def put(self, key, value):
# can assign to hash_ index
self._keys[hash_] = key
self._values[hash_] = value
self._len += 1
return
elif self._keys[hash_] == key:
# key already exists here, assign over
Expand Down Expand Up @@ -65,6 +69,7 @@ def del_(self, key):
# key found, assign with deleted sentinel
self._keys[hash_] = self._deleted
self._values[hash_] = self._deleted
self._len -= 1
return

hash_ = self._rehash(hash_)
Expand All @@ -84,6 +89,9 @@ def _rehash(self, old_hash):
def __getitem__(self, key):
return self.get(key)

def __delitem__(self, key):
return self.del_(key)

def __setitem__(self, key, value):
self.put(key, value)

Expand Down Expand Up @@ -127,7 +135,7 @@ def test_delete_key(self):
def test_delete_key_and_reassign(self):
m = HashTable(10)
m.put(1, 1)
m.del_(1)
del m[1]
m.put(1, 2)
self.assertEqual(2, m.get(1))

Expand Down

0 comments on commit 36a7561

Please sign in to comment.