Hash Functions

Hash Map

 

# Creating a hash table to store fruits based on their first letter
hash_table = {}
hash_table['A'] = 'Apple'
hash_table['B'] = 'Banana'
hash_table['O'] = 'Orange'

# Accessing a fruit based on its first letter
print(hash_table['A'])  # Output: 'Apple'
print(hash_table['B'])  # Output: 'Banana'
print(hash_table['O'])  # Output: 'Orange'

char_counting.gif

Hash Set

Example regular set:

# Regular Set (Without Hashing)
my_set = {3, 7, 1, 9, 5}

# Searching for an element in the set
search_element = 7
if search_element in my_set:
    print("Element found in the set!")
else:
    print("Element not found in the set.")

------------------------------------------------------
Example hashset:

# Hash Set (With Hashing)
my_hash_set = set()

# Adding elements to the hash set
my_hash_set.add(3)
my_hash_set.add(7)
my_hash_set.add(1)
my_hash_set.add(9)
my_hash_set.add(5)

# Searching for an element in the hash set
search_element = 7
if search_element in my_hash_set:
    print("Element found in the hash set!")
else:
    print("Element not found in the hash set.")