-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTable.py
99 lines (66 loc) · 2.33 KB
/
hashTable.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from doublyLinkedList import DoublyLinkedList
class HashNode:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self):
self._values = [DoublyLinkedList() for x in range(5)]
self._fill_factor = 0.75
self._count = 0
pass
def __iter__(self):
for linkedList in self._values:
for hashNode in linkedList:
yield hashNode
def __getitem__(self, key):
index = self._get_index(key)
linkedList = self._values[index]
for hashNode in linkedList:
if hashNode.key == key:
return hashNode.value
def __setitem__(self, key, value):
self.add(key, value)
def _get_index(self, key):
return (hash(key) % len(self._values))
def add(self, key, value):
if self.contains(key):
self.remove(key)
if self._count >= (len(self._values) * self._fill_factor):
self._extend()
index = self._get_index(key)
self._values[index].add_tail(HashNode(key, value))
self._count += 1
def _extend(self):
oldArray = self._values
self._values = [DoublyLinkedList() for x in range(len(oldArray) * 2)]
self._count = 0
for linkedList in oldArray:
if linkedList.get_count() > 0:
for hashNode in linkedList:
self.add(hashNode.key, hashNode.value)
def remove(self, key):
index = self._get_index(key)
linkedList = self._values[index]
nodeToRemove = None
notFound = True
for hashNode in linkedList:
if hashNode.key == key:
nodeToRemove = hashNode
notFound = False
break
if notFound:
raise ValueError("A node with the supplied key was not found")
else:
linkedList.remove(nodeToRemove)
self._count -= 1
def get_count(self):
return self._count
def contains(self, key):
index = self._get_index(key)
linkedList = self._values[index]
if linkedList.get_count() > 0:
for hashNode in linkedList:
if hashNode.key == key:
return True
return False