-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3. Hash_Table.py
61 lines (51 loc) · 1.77 KB
/
3. Hash_Table.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
class HashTable:
def __init__(self):
self.MAX = 10
self.arr = [[] for i in range(self.MAX)]
#The hash function
def get_hash(self, key):
h = 0
for char in key:
h += ord(char)
return h % self.MAX
def __setitem__(self, key, value):
hash = self.get_hash(key)
found = False
for index, element in enumerate(self.arr[hash]):
if len(element) == 2 and element[0] == key:
self.arr[hash][index] = (key, value)
found = True
break
if not found:
self.arr[hash].append((key, value))
def __getitem__(self, key):
hash = self.get_hash(key)
for element in self.arr[hash]:
if len(element) == 2 and element[0] == key:
return element[1]
return 'There is no such key-value pair!'
def __delitem__(self, key):
hash = self.get_hash(key)
for index, element in enumerate(self.arr[hash]):
if len(element) == 2 and element[0] == key:
del self.arr[hash][index]
return True
return 'There is no such key-value pair!'
if __name__ == '__main__':
samplehashtable = HashTable()
print(samplehashtable.get_hash('march 6'))
print(samplehashtable.get_hash('march 17'))
#__setitem__
samplehashtable['march 6'] = 310
samplehashtable['march 6'] = 110
samplehashtable['march 8'] = 380
samplehashtable['march 9'] = 302
samplehashtable['march 17'] = 450
#__getitem__
print(samplehashtable['march 79'])
print(samplehashtable['march 6'])
print(samplehashtable['march 17'])
#__delitem__
#del samplehashtable['march 9']
#del samplehashtable['march 6']
print(samplehashtable.arr)