|
| 1 | +# Hash Table |
| 2 | + |
| 3 | +From wikipedia |
| 4 | + |
| 5 | +> In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored. |
| 6 | +
|
| 7 | +## Time Complexity Analysis of Hash Table |
| 8 | + |
| 9 | +| Operation | Insertion | Deletion | Searching | |
| 10 | +|-----------------|-----------|----------|-----------| |
| 11 | +| Time Complexity | $O(1)$ (worst case: $O(n)$) | $O(1)$ (worst case: $O(n)$) | $O(1)$ (worst case: $O(n)$) | |
| 12 | + |
| 13 | +## 💻 Implementation in Python |
| 14 | + |
| 15 | +```python |
| 16 | +BLANK = object() |
| 17 | + |
| 18 | +class HashTable: |
| 19 | + def __init__(self, capacity) -> None: |
| 20 | + self.values = capacity * [BLANK] |
| 21 | + |
| 22 | + def __len__(self): |
| 23 | + return len(self.values) |
| 24 | + |
| 25 | + def __setitem__(self, key, value): |
| 26 | + self.values[self._index(key)] = value |
| 27 | + |
| 28 | + def __getitem__(self, key): |
| 29 | + value = self.values[self._index(key)] |
| 30 | + if value is BLANK: |
| 31 | + raise KeyError(key) |
| 32 | + return value |
| 33 | + |
| 34 | + def __contains__(self, key, default=None): |
| 35 | + try: |
| 36 | + self[key] |
| 37 | + except KeyError: |
| 38 | + return False |
| 39 | + else: |
| 40 | + return True |
| 41 | + |
| 42 | + def get(self, key, default=None): |
| 43 | + try: |
| 44 | + return self[key] |
| 45 | + except KeyError: |
| 46 | + return default |
| 47 | + |
| 48 | + def __delitem__(self, key): |
| 49 | + if key in self: |
| 50 | + self[key] = BLANK |
| 51 | + else: |
| 52 | + raise KeyError(key) |
| 53 | + |
| 54 | + def _index(self, key): |
| 55 | + return hash(key) % len(self) |
| 56 | + |
| 57 | +hash_table = HashTable(capacity=100) |
| 58 | +hash_table["key1"] = 1 |
| 59 | +print("key1" in hash_table) # True |
| 60 | +print(hash_table["key1"]) # 1 |
| 61 | +hash_table["key1"] = 2 |
| 62 | +print(hash_table["key1"]) # 2 |
| 63 | +del hash_table["key1"] |
| 64 | +print("key1" in hash_table) # False |
| 65 | +``` |
| 66 | + |
| 67 | +## 🔗 Further Reading |
| 68 | + |
| 69 | +* [Build a Hash Table in Python With TDD](https://realpython.com/python-hash-table/), realpython.com |
| 70 | +* [Python Hash Tables: Understanding Dictionaries](https://thepythoncorner.com/posts/2020-08-21-hash-tables-understanding-dictionaries/), thepythoncorner.com, 2020 |
| 71 | +* ▶️ [Hash Tables and Hash Functions](https://www.youtube.com/watch?v=KyUTuwz_b7Q), |
| 72 | +Computer Science, 2017 |
0 commit comments