77 lines
2.2 KiB
Python
77 lines
2.2 KiB
Python
class HashTable:
|
|
def __init__(self, capacity=10):
|
|
"""Vytvor prázdnu tabuľku s kladnou celočíselnou kapacitou."""
|
|
if type(capacity) is not int:
|
|
raise TypeError("It's not integer")
|
|
if capacity <= 0:
|
|
raise ValueError("Capacity > 0")
|
|
|
|
self._capacity = capacity
|
|
self._table = [None] * capacity
|
|
self._size = 0
|
|
|
|
|
|
|
|
@property
|
|
def capacity(self):
|
|
"""Vráť aktuálny počet pozícií v poli."""
|
|
return self.kapacity
|
|
|
|
def hash(self, key):
|
|
"""Vráť polynomiálny hash kľúča modulo aktuálna kapacita."""
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
h = 0
|
|
for znak in key:
|
|
h = (31 * h + ord(znak)) % self.capacity
|
|
return h
|
|
|
|
def probe(self, key):
|
|
"""Vráť index kľúča alebo miesta na vloženie bez zmeny tabuľky."""
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
start = self.hash(key)
|
|
first_deleted = None
|
|
|
|
def load_factor(self):
|
|
"""Vráť podiel počtu aktívnych položiek a kapacity."""
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
def __getitem__(self, key):
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
def __setitem__(self, key, value):
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
def __delitem__(self, key):
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
def __contains__(self, key):
|
|
if not isinstance(key, str):
|
|
raise TypeError("Key must be a string")
|
|
|
|
try:
|
|
index = self.probe(key)
|
|
except RuntimeError:
|
|
return False
|
|
|
|
item = self._table[index]
|
|
return (
|
|
item is not None
|
|
and item is not self._DELETED
|
|
and item[0] == key
|
|
)
|
|
def __len__(self):
|
|
return self._size
|
|
|
|
def __iter__(self):
|
|
for item in self._table:
|
|
if item is not None and item is not self._DELETED:
|
|
yield item[0]
|