-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhash_table_practice.py
55 lines (45 loc) · 1.28 KB
/
hash_table_practice.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
55
# get, set, remove
# hash_function, key linear search in bucket
class HashTable:
def __init__(self, capacity=256):
self.capacity = capacity
self.size = 0
self.buckets = [[] for _ in range(capacity)]
def __len__(self):
return self.size
def hash_fn(self, key):
hash = 0
for i in key:
hash = hash * 31 + ord(i)
return hash % self.capacity
def _find_bucket(self, key):
index = self.hash_fn(key)
return self.buckets[index]
def _find(self, key):
bucket = self._find_bucket(key)
for item in bucket:
if item[0] == key:
return bucket, item
return bucket, None
def set(self, key, value):
if not isinstance(key, str):
raise KeyError(key)
bucket, box = self._find(key)
if not box:
bucket.append([key, value])
self.size += 1
return
box[1] = value
def get(self, key):
_, box = self._find(key)
if not box:
raise KeyError(key)
return box[1]
def remove(self, key):
_, box = self._find(key)
if not box:
raise KeyError(key)
value = box[1]
del box
self.size -= 1
return value