Skip to content

Commit 36a7561

Browse files
committed
HashTable:
1. Fixed documentation 2. added __delitem__
1 parent ee36943 commit 36a7561

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

map/hashtable.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
1-
"""
2-
MAP Abstract Data Type
3-
Map() Create a new, empty map. It returns an empty map collection.
4-
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.
5-
get(key) Given a key, return the value stored in the map or None otherwise.
6-
del Delete the key-value pair from the map using a statement of the form del map[key].
7-
len() Return the number of key-value pairs stored in the map.
8-
in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
9-
"""
101
from unittest import TestCase
112

123

134
class HashTable(object):
5+
"""
6+
HashMap Data Type
7+
HashMap() Create a new, empty map. It returns an empty map collection.
8+
put(key, val) Add a new key-value pair to the map. If the key is already in the map then replace
9+
the old value with the new value.
10+
get(key) Given a key, return the value stored in the map or None otherwise.
11+
del_(key) or del map[key] Delete the key-value pair from the map using a statement of the form del map[key].
12+
len() Return the number of key-value pairs stored in the map.
13+
in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
14+
"""
15+
1416
_empty = object()
1517
_deleted = object()
1618

1719
def __init__(self, size=11):
1820
self.size = size
21+
self._len = 0
1922
self._keys = [self._empty] * size # keys
2023
self._values = [self._empty] * size # values
2124

@@ -27,6 +30,7 @@ def put(self, key, value):
2730
# can assign to hash_ index
2831
self._keys[hash_] = key
2932
self._values[hash_] = value
33+
self._len += 1
3034
return
3135
elif self._keys[hash_] == key:
3236
# key already exists here, assign over
@@ -65,6 +69,7 @@ def del_(self, key):
6569
# key found, assign with deleted sentinel
6670
self._keys[hash_] = self._deleted
6771
self._values[hash_] = self._deleted
72+
self._len -= 1
6873
return
6974

7075
hash_ = self._rehash(hash_)
@@ -84,6 +89,9 @@ def _rehash(self, old_hash):
8489
def __getitem__(self, key):
8590
return self.get(key)
8691

92+
def __delitem__(self, key):
93+
return self.del_(key)
94+
8795
def __setitem__(self, key, value):
8896
self.put(key, value)
8997

@@ -127,7 +135,7 @@ def test_delete_key(self):
127135
def test_delete_key_and_reassign(self):
128136
m = HashTable(10)
129137
m.put(1, 1)
130-
m.del_(1)
138+
del m[1]
131139
m.put(1, 2)
132140
self.assertEqual(2, m.get(1))
133141

0 commit comments

Comments
 (0)