""" hash.py A coding-in-class exercise to write a simple hash table. $ python hash.py The cat says meow Jim Mahoney | cs.marlboro.college | March 2022 | MIT License """ def hash_function(key): """ Given something (usually a string), return an integer """ result = "0" for letter in str(key): result = result + str(ord(letter)) return int(result) class HashTable: def __init__(self): self.size = 101 self.data = [None] * self.size def index(self, key): """ find the index i of this key """ tries = 0 max_tries = 5 index_key = key while tries < max_tries: tries += 1 i = hash_function(index_key) % self.size if self.data[i] == None: return i if self.data[i][0] == key: return i index_key += key return None def get(self, key): """ return corresponding value or None if not found """ i = self.index(key) if self.data[i][0] == None: return None if self.data[i][0] == key: return self.data[i][1] def insert(self, key, value): """ put (key,value) into the hash table """ i = self.index(key) if i==None: return self.data[i] = (key, value) def main(): hashtable = HashTable() # create a hash table hashtable.insert("cat", "meow") # insert some data into it meow = hashtable.get("cat") # fetch some data from it print("The cat says ", meow) main()