-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhashtable.py
More file actions
68 lines (51 loc) · 1.84 KB
/
hashtable.py
File metadata and controls
68 lines (51 loc) · 1.84 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
class hashtable(object):
def __init__(self,size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key,data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot]:
nextslot = self.rehash(nextslot,len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def hashfunction(self, key, size):
return key % size
def rehash(self,oldhash, size):
return (oldhash + 1) % size
def get(self,key):
startslot = self.hashfunction(key,len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position=self.rehash(position, len(self.slots))
if position == startslot:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self,key,data):
self.put(key,data)
h = hashtable(6)
h[1] = 'one'
h[2] = 'two'
h[3] = 'three'
h[4] = 'four'
print(h[3])