1
votes

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.

1
Which line gives the error? Please post the full error.dahui
I added it into the error statement, its the line which says position = key % self.capactiyM.Jones

1 Answers

2
votes

key ('hello') is a string object. You need to convert it to integer to do modulo. Otherwise it will perform printf-style string formatting; causes error because there's no % in the string:

position = key % self.capacity

Call self.hash to get hash value:

def insert(self, key): 
    position = self.hash(key) % self.capacity 
    if self.slots[position] == None: 
        self.slots[position] = key 
    else: 
        while self.slots[position] != None:
            position += 1
            if position >= self.capacity: 
                position = 0
        self.slots[position%self.capacity] = key
        return self.slots

UPDATE if body can be merged into else:

def insert(self, key): 
    position = self.hash(key) % self.capacity
    while self.slots[position] != None:
        position += 1
        if position >= self.capacity:
            position = 0
    self.slots[position%self.capacity] = key
    return self.slots