-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhash_chapter2_impl.py
More file actions
72 lines (53 loc) · 1.86 KB
/
hash_chapter2_impl.py
File metadata and controls
72 lines (53 loc) · 1.86 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from common import DUMMY, EMPTY
def create_new(from_keys):
n = len(from_keys)
hash_codes = [EMPTY for i in range(2 * n)]
keys = [EMPTY for i in range(2 * n)]
for key in from_keys:
hash_code = hash(key)
idx = hash_code % len(keys)
while keys[idx] is not EMPTY:
if hash_codes[idx] == hash_code and keys[idx] == key:
break
idx = (idx + 1) % len(keys)
hash_codes[idx] = hash_code
keys[idx] = key
return hash_codes, keys
def insert(hash_codes, keys, key):
hash_code = hash(key)
idx = hash_code % len(keys)
while hash_codes[idx] is not EMPTY:
if hash_codes[idx] == hash_code and keys[idx] == key:
return
idx = (idx + 1) % len(keys)
hash_codes[idx] = hash_code
keys[idx] = key
def remove(hash_codes, keys, key):
hash_code = hash(key)
idx = hash_code % len(keys)
while hash_codes[idx] is not EMPTY:
if hash_codes[idx] == hash_code and keys[idx] == key:
keys[idx] = DUMMY
return
idx = (idx + 1) % len(keys)
raise KeyError()
def has_key(hash_codes, keys, key):
hash_code = hash(key)
idx = hash_code % len(keys)
while hash_codes[idx] is not EMPTY:
if hash_codes[idx] == hash_code and keys[idx] == key:
return True
idx = (idx + 1) % len(keys)
return False
def resize(hash_codes, keys):
new_hash_codes = [EMPTY for i in range(len(hash_codes) * 2)]
new_keys = [EMPTY for i in range(len(keys) * 2)]
for hash_code, key in zip(hash_codes, keys):
if key is EMPTY or key is DUMMY:
continue
idx = hash_code % len(new_keys)
while new_hash_codes[idx] is not EMPTY:
idx = (idx + 1) % len(new_keys)
new_hash_codes[idx] = hash_code
new_keys[idx] = key
return new_hash_codes, new_keys