user5361938
user5361938

Reputation:

Code tracing and logical errors

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):
        slot = key % len(self.slots)

        if key in self.slots:
            return slot

        elif (not key in self.slots) and len(self.slots) == self.capacity:
            return slot

        else:
            for i in self.slots:
                count = 0 
                if i == None:
                    return count
                count += 1

    def insert(self, key):
        print(len(self.slots)) #Why does this show an output of 2? 
        if key in self.slots:
            return -2

        elif (not key in self.slots) and (len(self.slots) != self.capacity): #Now this cant execute
            num = hash_function(key)
            self.slots[num] = key
            return num

        elif (not key in self.slots) and len(self.slots) == self.capacity:
            return -1

Im wondering why the commented part above in the insert(self, key) the print statement gives (2) instead of (0). The elif statement underneath wont execute since its giving a result of (2) instead of (0)

A function call of

x = MyHashTable(2)
print(len(x)) 

Should give: 0

Upvotes: 1

Views: 81

Answers (2)

MSeifert
MSeifert

Reputation: 152647

You have to call your __len__ function (by calling self.__len__() ) if you want the length of the elements which are not None. For lists None are valid entries.

By the way. It is always best to compare with None by a is None or a is not None instead of == or !=.

Upvotes: 1

Thomas Orozco
Thomas Orozco

Reputation: 55197

You're initializing self.slots = [None] * self.capacity, so with capacity = 2, self.slots is [None, None], which is of length 2.

Your __len__ method doesn't run because len(self.slot) calls self.slot.__len__, not self.__len__. If you'd like to use your override method, you should be calling len(self) instead.

Upvotes: 1

Related Questions