Fast Reading / O(1)
In an unordered array, a search would take
O(N) steps adn O(log N) for an ordered array.
Using a data structure like hash table, we can make the search
O(1)!
menu = {'a': 1, 'b': 2, 'c': 3}
item = menu['b']
print(item)
Hash Function / Numbers
The process of taking characters and converting them
to numbers is called hashing.
mapping = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
def hashing(x: str) -> str:
hash = ''
for char in x:
hash += str(mapping[char])
return hash
def hashing_sum(x: str) -> int:
hash = 0
for char in x:
hash += mapping[char]
return hash
def hashing_product(x: str) -> int:
hash = 1
for char in x:
hash *= mapping[char]
return hash
print("Hashing | BAD =", hashing('BAD'))
print("Hasghing to Sum | BAD =", hashing_sum('BAD'))
print("Hasghing to Product | BAD =", hashing_product('BAD'))
Table Storage / Process
Let's imagine a simple thesaurus application to exemplify hash table
storing data proces.
The user search for an word and the app returns just one
synonym.
class MyHashTable:
def __init__(self):
self.table = [None] * 16
self.mapping = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
def hash_entry(self, x):
hash = 1
for char in x:
hash *= self.mapping[char]
return hash
def add_entry(self, key, value):
hash = self.hash_entry(key)
self.table[hash] = value
def get_entry(self, key):
hash = self.hash_entry(key)
return self.table[hash]
thesaurus = MyHashTable()
thesaurus.add_entry('bad', 'evil')
thesaurus.add_entry('cab', 'taxi')
value1 = thesaurus.get_entry('bad')
value2 = thesaurus.get_entry('cab')
print(value1)
print(value2)