I have been trying to write an insert(self, key): method for my MyHashTable: class.
It is supposed to use linear probing to handle collision resolution. If the key is already in the table then the method returns -2. If the key is not already in the table and there exists empty slots then the key is entered into the empty slot number returned by the hash_function and that slot number is returned. If the key is not in the hash table and there are no empty slots then it returns -1.
Here is my class:
class MyHashTable:
def __init__(self, capacity):
self.capacity = capacity
self.slots = [None] * self.capacity
def __str__(self):
return str(self.slots )
def __len__(self):
count = 0
for i in self.slots:
if i != None:
count += 1
return count
def hash_function(self, key):
i = key % self.capacity
return i
def insert(self, key):
slot = self.hash_function(key)
if key in self.slots[slot]:
return -2
elif key in self.slots[slot] == False:
return -1
else:
self.slots[slot].append(key)
return slot
The test is:
x = MyHashTable(2)
print("Add 3, return:", x.insert(3))
print("Hashtable:", x)
print("Add 3, return:", x.insert(3)) #duplicate
print("Hashtable:", x)
Result should be:
Add 3, return: 1
Hashtable: [None, 3]
Add 3, return: -2
Hashtable: [None, 3]
I tried a few methods but keep getting the error. "Nonetype" is not iterable.
passis not in the habit of iterating random collections :-) I suggest you add one of your attempts. - paxdiabloTracebackline; and to also post the section of code where that error occurs. If you'd done that it would've been immediately obvious to the people answering what was the cause of your problem. - PM 2Ring"Nonetype" is not iterablemessage because yourinsert()is attempting to appendkeytoNone. Actually, the logic of yourinsert()appears to treatself.slotsas if it were a list of lists. That is a legitimate way to organize a hash table, but it's not consistent with the rest of your class. - PM 2Ring