-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmap_functions.py
More file actions
64 lines (57 loc) · 2.12 KB
/
Copy pathHashmap_functions.py
File metadata and controls
64 lines (57 loc) · 2.12 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
class Hashmaps:
def __init__(self,capacity):
self.capacity=capacity
self.slots=[None]*self.capacity
self.value=[None]*self.capacity
self.size=0
def hash_function(self,key):
return abs(hash(key))% self.capacity
def rehash(self,old_hash):
return (old_hash+1)% self.capacity
def insert(self,key,value):
hash_value = self.hash_function(key)
if self.slots[hash_value] is None:
self.slots[hash_value]=key
self.value[hash_value]=value
self.size += 1
else:
if self.slots[hash_value]==key:
self.value[hash_value]=value
else:
new_hash = self.rehash(hash_value)
# Loop until empty slot or same key found
while self.slots[new_hash] is not None and self.slots[new_hash]!=key:
new_hash = self.rehash(new_hash)
if new_hash == hash_value: # avoids infinite loop in full table
break
if self.slots[new_hash]==None:
self.slots[new_hash]=key
self.value[new_hash]=value
self.size += 1
elif self.slots[new_hash]==key:
self.value[new_hash]=value
def get(self, key):
hash_value = self.hash_function(key)
index = hash_value
start_index = index
while self.slots[index] is not None:
if self.slots[index] == key:
return self.value[index]
index = self.rehash(index)
if index == start_index:
break
return None
def delete(self,key):
hash_value = self.hash_function(key)
index = hash_value
start_index = index
while self.slots[index] is not None:
if self.slots[index] == key:
self.slots[index] = None
self.value[index] = None
self.size -= 1
return
index = self.rehash(index)
if index == start_index:
break
return False