-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_tables.py
49 lines (40 loc) · 1.47 KB
/
hash_tables.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
# should always have a prime number of addresses to increase
# randomness to reduce collisions
class HashTable:
def __init__(self, size=7):
self.data_map = [None] * size
def __hash(self, key):
my_hash = 0
for letter in key:
my_hash = (my_hash + ord(letter) * 23) % len(self.data_map)
return my_hash
def print_table(self):
for i, val in enumerate(self.data_map):
print(i, ": ", val)
def set_item(self, key, value):
index = self.__hash(key)
if self.data_map[index] is None:
self.data_map[index] = []
self.data_map[index].append([key, value])
def get_item(self, key):
index = self.__hash(key)
if self.data_map[index] is not None:
for i in range(len(self.data_map[index])):
if self.data_map[index][i][0] == key:
return self.data_map[index][i][1]
return None
def keys(self):
all_keys = []
for i in range(len(self.data_map)):
if self.data_map[i] is not None:
for j in range(len(self.data_map[i])):
all_keys.append(self.data_map[i][j][0])
return all_keys
def item_in_common(self, list1, list2):
my_dict = {}
for i in list1:
my_dict[i] = True
for j in list2:
if j in my_dict:
return True
return False