|
| 1 | +```python |
| 2 | +class HashMap: |
| 3 | + def __init__(self, size): |
| 4 | + self.size = size |
| 5 | + self.hash_table = self.createBuckets() |
| 6 | + |
| 7 | + def createBuckets(self): |
| 8 | + return [[] for i in range(self.size)] |
| 9 | + |
| 10 | + def set(self, key, value): |
| 11 | + # get bucket hash |
| 12 | + bucket_hash = hash(key) % self.size |
| 13 | + bucket = self.hash_table[bucket_hash] |
| 14 | + |
| 15 | + found_key = False |
| 16 | + for idx, record in enumerate(bucket): |
| 17 | + record_key, record_val = record |
| 18 | + if record_key == key: |
| 19 | + found_key = True |
| 20 | + break |
| 21 | + if found_key: |
| 22 | + bucket[idx] = (key, value) |
| 23 | + else: |
| 24 | + bucket.append((key, value)) |
| 25 | + |
| 26 | + def get(self, key): |
| 27 | + # Get the index of the bucket holding the key using the hash function |
| 28 | + index = hash(key) % self.size |
| 29 | + |
| 30 | + # get the bucket using the index |
| 31 | + bucket = self.hash_table[index] |
| 32 | + |
| 33 | + found_key = False |
| 34 | + for idx, record in enumerate(bucket): |
| 35 | + record_key, record_val = record |
| 36 | + if key == record_key: |
| 37 | + found_key = True |
| 38 | + break |
| 39 | + return record_val if found_key else None |
| 40 | + |
| 41 | + def delete(self, key): |
| 42 | + bucket_hash = hash(key) % self.size |
| 43 | + found_key = False |
| 44 | + for idx, record in enumerate(self.hash_table[bucket_hash]): |
| 45 | + record_key, record_value = record |
| 46 | + if key == record_key: |
| 47 | + found_key = True |
| 48 | + break |
| 49 | + if found_key: |
| 50 | + # delete |
| 51 | + self.hash_table.pop(idx) |
| 52 | + else: |
| 53 | + return f"Key '{key}' does not exist" |
| 54 | + |
| 55 | + |
| 56 | +``` |
| 57 | + |
| 58 | + |
| 59 | +```python |
| 60 | +hashmap = HashMap(10) |
| 61 | +``` |
| 62 | + |
| 63 | + |
| 64 | +```python |
| 65 | +hashmap.set("something", "soweto") |
| 66 | +for i in range(5): |
| 67 | + hashmap.set(f"{i}", i) |
| 68 | +``` |
| 69 | + |
| 70 | + |
| 71 | +```python |
| 72 | +hashmap.get("something") |
| 73 | + |
| 74 | +``` |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + 'soweto' |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +```python |
| 85 | + |
| 86 | +``` |
0 commit comments