Skip to content

Commit 097fdac

Browse files
committed
HashTables.py changed
1 parent 1d877a8 commit 097fdac

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

DataStructures/Section7/HashTables.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,47 @@ def growth(self):
7070
self.size = new_hash_table.size
7171
self.slots = new_hash_table.slots
7272

73+
def get(self, key):
74+
h = self._hash(key)
75+
while self.slots[h]!=None:
76+
if self.slots[h].key == key:
77+
return self.slots[h].value
78+
h = (h+1)%self.size
79+
return None
80+
81+
#implement hashtable as dictionary
82+
def __setitem__(self, key, value):
83+
self.put(key, value)
84+
85+
def __getitem__(self, key):
86+
return self.get(key)
87+
88+
#quadratic probing vs linear probing
89+
def get_quadratic(self, key):
90+
h = self._hash(key)
91+
j = 1
92+
while self.slots[h] != None:
93+
if self.slots[h].key == key:
94+
return self.slots[h].value
95+
h = (h+ j**2) % self.size
96+
j = j + 1
97+
return None
98+
99+
def put_quadratic(self, key, value):
100+
item = HashItem(key, value)
101+
h = self._hash(key)
102+
j = 1
103+
while self.slots[h] != None:
104+
if self.slots[h].key == key:
105+
break
106+
h = (h + j*j) % self.size
107+
j = j+1
108+
if self.slots[h] == None:
109+
self.count += 1
110+
self.slots[h] = item
111+
self.check_growth()
112+
113+
73114
ht = HashTable()
74115
ht.put("good", "eggs")
75116
ht.put("better", "ham")
@@ -79,3 +120,38 @@ def growth(self):
79120
ht.put("awd", "do not")
80121
ht.put("add", "do not")
81122
ht.check_growth()
123+
124+
print("++++++++++++++++++")
125+
126+
ht = HashTable()
127+
ht.put("good", "eggs")
128+
ht.put("better", "ham")
129+
ht.put("best", "spam")
130+
ht.put("ad", "do not")
131+
ht.put("ga", "collide")
132+
for key in ("good", "better", "best", "worst", "ad", "ga"):
133+
v = ht.get(key)
134+
print(v)
135+
136+
#implement as dictionary
137+
print("///////////")
138+
ht = HashTable()
139+
ht["good"] = "eggs"
140+
ht["better"] = "ham"
141+
ht["best"] = "spam"
142+
ht["ad"] = "do not"
143+
ht["ga"] = "collide"
144+
for key in ("good", "better", "best", "worst", "ad", "ga"):
145+
v = ht[key]
146+
print(v)
147+
print("The number of elements is: {}".format(ht.count))
148+
149+
#quadratic probing
150+
print("--------------------------")
151+
ht = HashTable()
152+
ht.put_quadratic("good", "eggs")
153+
ht.put_quadratic("ad", "packt")
154+
ht.put_quadratic("ga", "books")
155+
156+
v = ht.get_quadratic("ga")
157+
print(v)

0 commit comments

Comments
 (0)