|
| 1 | + |
| 2 | +# CONSTRUCT A HASH TABLE |
| 3 | +# ------------------------ |
| 4 | + |
| 5 | +single_hash_table = [None] * 10 |
| 6 | +print(single_hash_table) |
| 7 | + |
| 8 | +# Output: |
| 9 | +# [None, None, None, None, None, None, None, None, None, None] |
| 10 | + |
| 11 | +# Below is a simple hash function that returns the modulus of the length of the hash table. |
| 12 | +# In our case, the length of the hash table is 10. |
| 13 | + |
| 14 | +# (Modulo operator (%) is used in the hashing function. The % (modulo) operator yields the remainder from the division |
| 15 | +# of the first argument by the second.) |
| 16 | + |
| 17 | + |
| 18 | +def hashing_func(key): |
| 19 | + return key % len(hash_table) |
| 20 | + |
| 21 | + |
| 22 | +def insert(hash_table, key, value): |
| 23 | + hash_key = hashing_func(key) |
| 24 | + hash_table[hash_key] = value |
| 25 | + |
| 26 | + |
| 27 | +insert(single_hash_table, 10, 'Nepal') |
| 28 | +print(single_hash_table) |
| 29 | +# Output: |
| 30 | +# ['Nepal', None, None, None, None, None, None, None, None, None] |
| 31 | + |
| 32 | +insert(single_hash_table, 25, 'USA') |
| 33 | +print(single_hash_table) |
| 34 | +# Output: |
| 35 | +# ['Nepal', None, None, None, None, 'USA', None, None, None, None] |
| 36 | + |
| 37 | + |
| 38 | +# WE HAVE A PROBLEM, "Collision" |
| 39 | +# A collision occurs when two items/values get the same slot/index, i.e. |
| 40 | +# the hashing function generates same slot number for multiple items. |
| 41 | +# If proper collision resolution steps are not taken then the previous item in the slot will be replaced by the |
| 42 | +# new item whenever the collision occurs. |
| 43 | + |
| 44 | +# TO RESOLVE ABOVE COLLISION PROBLEM, WE HAVE TWO TYPES |
| 45 | + |
| 46 | +# 1. LINEAR PROBING |
| 47 | +# 2. CHAINING |
| 48 | + |
| 49 | + |
| 50 | +# ####### NEEDS UPDATE ##### |
0 commit comments