Хеширование без встроенной функции - PullRequest
0 голосов
/ 10 октября 2019

Я хочу вставить элементы с разными слотами без использования встроенной функции Python

class MyHashTable:
    def __init__(self, capacity):
        self.capacity = capacity
        self.slots = [None] * self.capacity
        self.count = 0


    def __str__(self):
        return str(self.slots)


    def __contains__(self, item):
        return self.search(item) != -1


    def __len__(self):
        return self.count


    def hash_function(self, key):
        return hash(key) % self.capacity


    def find_slot(self, key):
        slot = self.hash_function(key)
        while self.slots[slot] is not None and self.slots[slot] != key:
            slot = (slot + 1) % self.capacity
        return slot


    def insert(self, key):
        slot = self.find_slot(key)  # int(input("Enter the slot number:"))

        if self.slots[slot] != key:
            self.slots[slot] = key
            self.count += 1


    def search(self, key):
        i = self.find_slot(key)
        if self.slots[i] is not None:
            return i
        return -1


    def displayall(self):
        current = self.slots
        while current:
            print(current, end=' ')
            break

if __name__ == '__main__':

    try:
        while True:
            m = MyHashTable(10)
            n = int(input(
                "\nPress \n 1. To Insert the Data \n 2. To Search the Data \n 3. To Find the Length of Hash Function \n 4. Exit \n"))

            if n == 1:
                data = int(input(" Enter the data: "))
                print(" Data inserted Successfully ", m.insert(data))
                m.displayall()

            if n == 2:
                key = int(input(" Enter the data: "))
                print(m.__contains__(key))

            if n == 3:
                print(" Length of Hash Function is ", len(m))

            if n == 4:
                exit()

    except ValueError:
        print("Enter the Proper option: ")

    except KeyboardInterrupt:
        print("Force Quit")

Вывод:

Press 
 1. To Insert the Data 
 2. To Search the Data 
 3. To Find the Length of Hash Function 
 4. Exit 
1
 Enter the data: 100
 Data inserted Successfully  None
[100, None, None, None, None, None, None, None, None, None] 
Press 
 1. To Insert the Data 
 2. To Search the Data 
 3. To Find the Length of Hash Function 
 4. Exit 
1
 Enter the data: 200
 Data inserted Successfully  None
[200, None, None, None, None, None, None, None, None, None] 
Press 
 1. To Insert the Data 
 2. To Search the Data 
 3. To Find the Length of Hash Function 
 4. Exit 

Я хочу вставить элемент в таблицу и хочуискать элементы без столкновения элементов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...