"""Hashtables (associative arrays)"""# linear probingclassHashTable(object):def__init__(self): self.size =10 self.keys = [None] * self.size self.values = [None] * self.sizedefput(self,key,data): index = self.hashfunction(key)# not None -> it is a collision !!!while self.keys[index]isnotNone:if self.keys[index]== key: self.values[index]= data # updatereturn# rehash try to find another slot index = (index +1) % self.size# insert self.keys[index]= key self.values[index]= datadefget(self,key): index = self.hashfunction(key)while self.keys[index]isnotNone:if self.keys[index]== key:return self.values[index] index = (index +1) % self.size# it means the key is not present in the associative arrayreturnNonedefhashfunction(self,key):sum=0for pos inrange(len(key)):sum=sum+ord(key[pos])returnsum% self.sizetable =HashTable()table.put("apple", 10)table.put("orange", 20)table.put("car", 30)table.put("table", 40)print(table.get("car"))
Hash Table
Describe an implementation of a least-used cache, and big-O notation of it.
A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
Implement data structure Map storing pairs of integers (key, value) and define following member functions in O(1) runtime: void insert(key, value), void delete(key), int get(key), int getRandomKey().
"""Write a HashTable class that stores stringsin a hash table, where keys are calculatedusing the first two letters of the string."""classHashTable(object):def__init__(self): self.table = [None]*10000defstore(self,string):"""Input a string that's stored in the table.""" index = self.calculate_hash_value(string)if(self.lookup(string)==-1): self.table[index]= [string]else: self.table[index].append(string)passdeflookup(self,string):"""Return the hash value if the string is already in the table. Return -1 otherwise.""" index = self.calculate_hash_value(string)if(self.table[index]!=None):return indexelse:return-1defcalculate_hash_value(self,string):"""Helper function to calulate a hash value from a string.""" hash_val =ord(string[0])*100+ord(string[1])return hash_val# Setuphash_table =HashTable()# Test calculate_hash_value# Should be 8568print hash_table.calculate_hash_value('UDACITY')# Test lookup edge case# Should be -1print hash_table.lookup('UDACITY')# Test storehash_table.store('UDACITY')# Should be 8568print hash_table.lookup('UDACITY')# Test store edge casehash_table.store('UDACIOUS')# Should be 8568print hash_table.lookup('UDACIOUS')#print(hash_table.table)