Trying to add an insert(self, key) method that inserts the key into the appropriate position while linear probing for resolving collisions. My current code, I'm just not 100% sure how to inset the str into the hash table.
Testing code:
#Test
my_table = HashTable(5)
my_table.insert('hello')
print("Hashtable:", my_table)
result:
Hashtable: [None, None, None, None, 'hello']
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
self.slots = [None] * self.capacity
def __str__(self):
return str(self.slots )
def is_empty(self):
return self.slots.count(None) == len(self.slots)
def hash(self, key):
sum = 0
for char in key:
sum += ord(char)
sum2 = "%04d" % (sum)
digits = int((sum2[2]) + (sum2[3]))
number = int(digits * digits)
return number % len(self.slots)
def insert(self, key):
count = 0
position = key%self.capacity
if self.slots[key%self.capacity] == None:
self.slots[key%self.capacity] = key
else:
while self.slots[position] != None:
position +=1
if position >= self.capacity:
position = 0
self.slots[position%self.capacity] = key
return self.slots
Im currently getting a Type error
>>>TypeError: not all arguments converted during string formatting line 25, in insert
position = key%self.capacity
I just need some advice on how to add the string into the hash table.