MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / __delitem__

Method __delitem__

data_structures/hashing/hash_map.py:206–265  ·  view source on GitHub ↗

>>> hm = HashMap(5) >>> hm._add_item(1, 10) >>> hm._add_item(2, 20) >>> hm._add_item(3, 30) >>> hm.__delitem__(3) >>> hm HashMap(1: 10, 2: 20) >>> hm = HashMap(5) >>> hm._add_item(-5, 10) >>> hm._add_item(6, 30)

(self, key: KEY)

Source from the content-addressed store, hash-verified

204 self._add_item(key, val)
205
206 def __delitem__(self, key: KEY) -> None:
207 """
208 >>> hm = HashMap(5)
209 >>> hm._add_item(1, 10)
210 >>> hm._add_item(2, 20)
211 >>> hm._add_item(3, 30)
212 >>> hm.__delitem__(3)
213 >>> hm
214 HashMap(1: 10, 2: 20)
215 >>> hm = HashMap(5)
216 >>> hm._add_item(-5, 10)
217 >>> hm._add_item(6, 30)
218 >>> hm._add_item(-7, 20)
219 >>> hm.__delitem__(-5)
220 >>> hm
221 HashMap(6: 30, -7: 20)
222
223 # Trying to remove a non-existing item
224 >>> hm = HashMap(5)
225 >>> hm._add_item(1, 10)
226 >>> hm._add_item(2, 20)
227 >>> hm._add_item(3, 30)
228 >>> hm.__delitem__(4)
229 Traceback (most recent call last):
230 ...
231 KeyError: 4
232
233 # Test resize down when sparse
234 ## Setup: resize up
235 >>> hm = HashMap(initial_block_size=100, capacity_factor=0.75)
236 >>> len(hm._buckets)
237 100
238 >>> for i in range(75):
239 ... hm[i] = i
240 >>> len(hm._buckets)
241 100
242 >>> hm[75] = 75
243 >>> len(hm._buckets)
244 200
245
246 ## Resize down
247 >>> del hm[75]
248 >>> len(hm._buckets)
249 200
250 >>> del hm[74]
251 >>> len(hm._buckets)
252 100
253 """
254 for ind in self._iterate_buckets(key):
255 item = self._buckets[ind]
256 if item is None:
257 raise KeyError(key)
258 if item is _deleted:
259 continue
260 if item.key == key:
261 self._buckets[ind] = _deleted
262 self._len -= 1
263 break

Callers

nothing calls this directly

Calls 3

_iterate_bucketsMethod · 0.95
_is_sparseMethod · 0.95
_size_downMethod · 0.95

Tested by

no test coverage detected