Skip to content

Instantly share code, notes, and snippets.

@imxdn
Last active May 7, 2016 16:17
Show Gist options
  • Select an option

  • Save imxdn/076cbaf8e90eb5317b286d416372b515 to your computer and use it in GitHub Desktop.

Select an option

Save imxdn/076cbaf8e90eb5317b286d416372b515 to your computer and use it in GitHub Desktop.
class HashTable:
def __init__(self, size):
self.size = size
self.slots = [None] * size
self.data = [None] * size
def insert(self, key, data):
hashval = self._hash(key)
if self.slots[hashval] == None:
self.slots[hashval] = key
self.data[hashval] = data
print("Insertion successful")
else:
print("Slot already occupied!")
def search(self, key):
hashval = self._hash(key)
if self.slots[hashval] != None:
print("Item found {} with key value {}".format(self.data[hashval], key))
else:
print("Key not found")
def _hash(self, key):
'''
If key is a string, sum up the ASCII values of each character and mod by number of slots
else if an integer, mod with directly with number of slots.
'''
if type(key) == int:
hv = key%(self.size)
return hv
else:
sum = 0
for _ in range(0, len(key)):
sum += ord(key[_])
hv = sum%(self.size)
return hv
H = HashTable(11)
while(True):
ch = int(input("""
(1) Insert
(2) Search
(3) Quit
"""))
if ch == 1:
key, data = input("Enter key,data: ").split(',')
H.insert(key, data)
elif ch == 2:
key = input("Enter the key to search: ")
H.search(key)
elif ch == 3:
quit()
else:
print("Invalid choice, please try again...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment