1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class HashTable: def __init__(self, size: int, bucket_size: int): self.size = size self.table = [] self.bucket_size = bucket_size self.extra = [] for i in range(size): for j in range(bucket_size): self.table.append(None)
def insert(self, content): flag = True index = hash(content) % self.size for i in range(index * self.bucket_size, (index + 1) * self.bucket_size): if self.table[i] is None or self.table[i] == content: self.table[i] = content flag = False break if flag: self.extra.append(content)
def search(self, content): index = hash(content) % self.size for i in range(index * self.bucket_size, (index + 1) * self.bucket_size): if self.table[i] == content: return True for cache in self.extra: if cache == content: return True return False
def pretty_print(self): for index in range(self.size): cache = [] for i in range(index * self.bucket_size, (index + 1) * self.bucket_size): cache.append(self.table[i]) print(f"bucket:{index} value:{cache}") print(f"extra: {self.extra}")
|