-
Notifications
You must be signed in to change notification settings - Fork 0
/
chaining.py
58 lines (50 loc) · 1.53 KB
/
chaining.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
56
57
58
from linklist import *
class Chaining(object):
def __init__(self):
self.N = 373
self.alpha = 0
self.cnt = 0
self.n_encountered = 0
self.table = [LinkList() for i in range(self.N)]
def hash(self, key):
return key % self.N
def search(self, key):
k = self.hash(key)
return self.table[k].search(key)
def insert(self, key, val):
k = self.hash(key)
isExisted = (self.table[k].search(key) != -1)
node, cnt = self.table[k].insert(key, val)
self.n_encountered += cnt
if not isExisted:
self.cnt += 1
self.alpha = self.cnt / self.N
if self.alpha >= 1:
self.N *= 2
self.rehash()
def remove(self, key):
k = self.hash(key)
isExisted = (self.table[k].search(key) != -1)
self.table[k].remove(key)
if not isExisted:
self.cnt -= 1
self.alpha = self.cnt / self.N
if self.alpha <= 0.25:
self.N /= 2
self.rehash()
def rehash(self):
all = []
self.cnt = 0
for lst in self.table:
head = lst.head
while head:
kv = head.kv
all.append(kv)
head = head.next
self.table = [LinkList() for i in range(0, self.N)]
for kv in all:
self.insert(kv.key, kv.val)
def prompt(self):
for i in range(0, self.N):
print(i, ':')
self.table[i].prompt()