0

Я не могу понять как написать метод insert.

Вот код, который пока что готов:

class HashTable:

def __init__(self):
    # ограничение на 4 слота 
    self._content = [[], [], [], []]


def get_hash(self, key):
   if key == '':

      return 3

   return ord(key[0]) * len(key)

# нужно использовать self.get_hash() но не знаю как именно лучше

def insert(self, key, value):
    # хэш-функция
    hash_key = hash(key) % len(self._content)
    key_exists = False
    bucket = self._content[hash_key]
    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            key_exists = True
            break
    if key_exists:
        bucket[i] = (key, value)
    else:
        bucket.append((key, value))


Примерно как должно работать:
h = HashTable()
h.insert('a', 'b')
print(h)
0: []
1: [('a', 'b')]
2: []
3: []

h.insert('apple', 'bee')
0: []
1: [('a', 'b'), ('apple', 'bee')]
2: []
3: []

h.insert('apple', 'juice')
0: []
1: [('a', 'b'), ('apple', 'juice')]
2: []
3: []

Буду признателен за любую помощь!

1 ответ 1

1

Вычисление этого ключа

hash_key = hash(key) % len(self._content)

происходит неверно. Нужно просто изменить на

hash_key = self.get_hash(key) % len(self._content)
1
  • Ой, даже не заметил ! Спасибо большое
    – User007
    15 авг 2018 в 18:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.