-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashing.py
55 lines (37 loc) · 1.23 KB
/
hashing.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/local/bin/python3
from typing import Dict, List
class HashTableLimitException(Exception):
pass
class Table:
items: Dict[int, List[str]] = {}
size: int
elements: int
def __init__(self, size: int):
self.size = size
self.elements = 0
pass
def hash(self, value: str) -> str:
return hash(value) % self.size
def add(self, value: str) -> None:
if self.elements >= self.size:
raise HashTableLimitException(f"{self.size} items already exist.")
self.elements += 1
index: int = self.hash(value)
if index in self.items:
update: List[str] = self.items[index] + [value]
else:
update: List[str] = [value]
self.items.update({index: update})
def __repr__(self) -> str:
return '\n'.join([
f"{self.items[k]} -> {k}"
for k in self.items
])
def __len__(self) -> int:
return self.elements
def lookup(self, value: str) -> (int, str):
hash: int = self.hash(value)
items: List[str] = self.items[hash] or []
if value not in items:
return -1, ""
return hash, self.items[hash] or ''