|
| 1 | +# Author: OMKAR PATHAK |
| 2 | + |
| 3 | +# In computing, a hash table (hash map) is a data structure which implements an associative array abstract |
| 4 | +# data type, a structure that can map keys to values. A hash table uses a hash function to compute an index |
| 5 | +# into an array of buckets or slots, from which the desired value can be found. |
| 6 | + |
| 7 | +# Python's built-in data type dictionary uses hash tables to retrieve key value pairs. |
| 8 | + |
| 9 | +class HashMap(object): |
| 10 | + def __init__(self): |
| 11 | + self.hash_map = [[(None, None)] for _ in range(10)] |
| 12 | + |
| 13 | + def insert(self, key, value): |
| 14 | + hash_key = hash(key) % len(self.hash_map) |
| 15 | + key_exists = 0 |
| 16 | + hash_list = self.hash_map[hash_key] |
| 17 | + # print(key, value) |
| 18 | + for i, key_value_pair in enumerate(hash_list): |
| 19 | + key_in_table, value_in_table = key_value_pair |
| 20 | + if key == key_in_table or key_in_table == None: |
| 21 | + key_exists = 1 |
| 22 | + if key_exists: |
| 23 | + hash_list[i] = ((key, value)) |
| 24 | + else: |
| 25 | + hash_list.append((key, value)) |
| 26 | + |
| 27 | + def get(self, key): |
| 28 | + hash_key = hash(key) % len(self.hash_map) |
| 29 | + hash_list = self.hash_map[hash_key] |
| 30 | + for i, key_value in enumerate(hash_list): |
| 31 | + key_in_table, value_in_table = key_value |
| 32 | + return value_in_table |
| 33 | + raise KeyError |
| 34 | + |
| 35 | +if __name__ == '__main__': |
| 36 | + myDict = HashMap() |
| 37 | + myDict.insert('Omkar', 'Pathak') |
| 38 | + myDict.insert('Jagdish', 'Pathak') |
| 39 | + value = myDict.get('Omkar') |
| 40 | + print(value) |
0 commit comments